Welcome

首页 / 软件开发 / C# / C#控制鼠标操作

C#控制鼠标操作2010-06-25控制鼠标操作包括很多种,如限定鼠标的移动范围、设置鼠标的左右键、控制鼠标的显示和隐藏等。本节中将通过两个具体的示例来介绍有关控制鼠标操作方面的知识。

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();