程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#處理鼠標和鍵盤事件(2)

C#處理鼠標和鍵盤事件(2)

編輯:關於C語言
(2).鼠標相關事件中的典型問題處理辦法:

在掌握了C#中定義和鼠標相關的事件,我們就來探討一下和鼠標相關事件的典型問題。其一是讀取鼠標的當前位置;其二是判定到底是那個鼠標按鍵按動。

判定鼠標的位置可以通過事件"MouseMove"來處理,在"MouseEventArgs"類中提供了二個屬性"X"和"Y",來判定當前鼠標縱坐標和橫坐標。而判定鼠標按鍵的按動情況,可以通過事件"MouseDown"來處理,並且在"MouseEventArgs"類中也提供了一個屬性"Button"來判定鼠標按鍵情況。根據這些知識,可以得到用C#編寫的讀取鼠標當前位置和判定鼠標按鍵情況的程序代碼。下面就是此代碼(mouse.cs)和此代碼編譯後運行界面:

圖01:用C#讀取鼠標位置和鼠標按鍵的程序運行界面

mouse.cs的源程序代碼如下:

using System ;
using System.Drawing ;
using System.Collections ;
using System.ComponentModel ;
using System.Windows.Forms ;
using System.Data ;
public class Form1 : Form
{
private System.ComponentModel.Container components = null ;
public Form1 ( )
{
file://初始化窗體中的各個組件
InitializeComponent ( ) ;
}
file://清除程序中使用過的資源
protected override void Dispose ( bool disposing )
{
if ( disposing )
{
if (components != null)
{
components.Dispose ( ) ;
}
}
base.Dispose ( disposing ) ;
}
private void InitializeComponent ( )
{
this.AutoScaleBaseSize = new System.Drawing.Size ( 6 , 14) ;
this.ClIEntSize = new System.Drawing.Size ( 292 , 273 ) ;
this.Name = "Form1" ;
this.Text = "C#處理鼠標按動事件!" ;
file://為鼠標按動定義一個事件處理過程"Form1_MouseDown"
this.MouseDown += new MouseEventHandler ( Form1_MouseDown ) ;
file://為鼠標移動定義一個事件處理過程"Form1_MouseMove"
this.MouseMove += new MouseEventHandler ( Form1_OnMouseMove ) ;
}
static void Main ( )
{
Application.Run ( new Form1 ( ) ) ;
}
private void Form1_OnMouseMove ( object sender , MouseEventArgs e )
{
this.Text = "當前鼠標的位置為:( " + e.X + " , " + e.Y + ")" ;
}
private void Form1_MouseDown ( object sender , MouseEventArgs e )
{
file://響應鼠標的不同按鍵
if ( e.Button == MouseButtons.Left )
{
MessageBox.Show ( "按動鼠標左鍵!" ) ;
}
if ( e.Button == MouseButtons.Middle )
{
MessageBox.Show ( "按動鼠標中鍵!") ;
}
if ( e.Button == MouseButtons.Right )
{
MessageBox.Show ( "按動鼠標右鍵!") ;
}
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved