控制鼠標操作包括很多種,如限定鼠標的移動范圍、設置鼠標的左右鍵、控制鼠標的顯示和隱藏等。本節中將通過兩個具體的示例來介紹有關控制鼠標操作方面的知識。
1.限定鼠標的移動范圍
利用API函數ClipCursor和GetWindowRect可以實現限定鼠標移動范圍的功能。API函數聲明如下:
[System.Runtime.InteropServices.DllImport("user32", EntryPoint = "ClipCursor")]
public extern static int ClipCursor(ref RECT lpRect);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetWindowRect")]
public extern static int GetWindowRect(int hwnd, ref RECT lpRect);
示例 控制鼠標移動
本示例通過API函數ClipCursor和GetWindowRect實現了限定鼠標移動范圍的功能。
程序主要代碼如下。
單擊【控制鼠標移動】按鈕,鼠標只能在窗體中移動,關鍵代碼如下:public struct RECT//聲明參數的值
單擊【恢復移動】按鈕,鼠標恢復移動,關鍵代碼如下:
{
public int left;
public int top;
public int right;
public int bottom;
}
public void Lock(System.Windows.Forms.Form ObjectForm)
{
RECT _FormRect = new RECT();
GetWindowRect(ObjectForm.Handle.ToInt32(), ref _FormRect);
ClipCursor(ref _FormRect);
}public void UnLock()
{
RECT _ScreenRect = new RECT();
_ScreenRect.top = 0;
_ScreenRect.left = 0;
_ScreenRect.bottom = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Bottom;
_ScreenRect.right = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Right;
ClipCursor(ref _ScreenRect); }
2.鼠標設置
設置鼠標包括設置鼠標的左右鍵、顯示與隱藏鼠標和設置雙擊鼠標的時間間隔等。通常使用API函數SwapMouseButton、ShowCursor、SetDoubleClickTime和GetDoubleClickTime對鼠標進行設置。這幾個函數的聲明如下:
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SwapMouseButton")]
public extern static int SwapMouseButton(int bSwap);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "ShowCursor")]
public extern static bool ShowCursor(bool bShow);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetDoubleClickTime")]
public extern static int SetDoubleClickTime(int wCount);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetDoubleClickTime")]
public extern static int GetDoubleClickTime();