有时,我们需在我们的程序中模拟鼠标的移动、点击等动作。——比如,一个再现用户操作的宏,或者一个演示操作方法的Demo程序。那么,我们在.Net中如何实现呢?.Net并没有提供改变鼠标指针位置、模拟点击操作的函数;但是Windows API提供了。其中一个是:
[DllImport("user32.dll")] static extern bool SetCursorPos(int X, int Y);
该函数可以改变鼠标指针的位置。其中X,Y是相对于屏幕左上角的绝对位置。另一个函数是:
[DllImport("user32.dll")] static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
这个函数不仅可以设置鼠标指针绝对的位置,而且可以以相对坐标来设置。另外,该函数还可以模拟鼠标左右键点击、鼠标滚轮操作等。其中的MouseEventFlag是一个基于uint类型的枚举,定义如下:
[Flags] enum MouseEventFlag : uint { Move = 0x0001, LeftDown = 0x0002, LeftUp = 0x0004, RightDown = 0x0008, RightUp = 0x0010, MiddleDown = 0x0020, MiddleUp = 0x0040, XDown = 0x0080, XUp = 0x0100, Wheel = 0x0800, VirtualDesk = 0x4000, Absolute = 0x8000 }
关于这两个函数的详细说明,可以查看MSDN Library或者Windows的Platform SDK文档。下面的演示程序(完整版源代码,VS.Net 2005/C#)演示了使用上面的函数,控制鼠标移动到任务栏并点击“开始”按钮的方法。(该程序使用了FindWindowEx等API函数来查找任务栏及开始菜单)
原代码:https://files.cnblogs.com/smalldust/SimulateMouse.zip
原文地址:http://www.cnblogs.com/eaglet/archive/2009/07/24/1529920.html
public partial class DemoForm : Form
{
[Flags]
enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000
}
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
const int AnimationCount = 80;
private Point endPosition;
private int count;
public DemoForm()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
endPosition.X = 1293;//设置目的地 X
endPosition.Y = 884; //设置目的地 Y
if (chkAnimation.Checked)//有过程
{
this.count = AnimationCount;
movementTimer.Start();
}
else
{
//直接执行设定
SetCursorPos(endPosition.X, endPosition.Y);
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
}
private void movementTimer_Tick(object sender, EventArgs e)//即使开始运行过程
{
int stepx = (endPosition.X - MousePosition.X) / count;
int stepy = (endPosition.Y - MousePosition.Y) / count;
count--;
if (count == 0)
{
movementTimer.Stop();
//SetCursorPos(endPosition.X, endPosition.Y);//强制最终坐标
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
tbCursor.Text = String.Format("({0}, {1})", MousePosition.X, MousePosition.Y);
mouse_event(MouseEventFlag.Move, stepx, stepy, 0, UIntPtr.Zero);
}
}