我想做的是操纵鼠标。这将是一个为了我自己目的而设计的简单宏。因此,它将移动我的鼠标到屏幕上的特定位置,并以特定间隔点击,就像我自己在点击一样。
以下是使用不受管理的函数模拟鼠标点击的代码:
//This is a replacement for Cursor.Position in WinForms
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}
为了让鼠标按下一定时间,您可以Sleep()
执行此函数的线程,例如:
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
System.Threading.Thread.Sleep(1000);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
以上代码将使鼠标保持按下状态1秒钟,除非用户按下并释放鼠标按钮。此外,请确保不要在主UI线程上执行此代码,否则会导致其挂起。
windows.Forms.Cursor.Position = New System.Drawing.Point(Button1.Location.X + Me.Location.X + 50, Button1.Location.Y + Me.Location.Y + 30)
:
using System.Runtime.InteropServices;
private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
[DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, uint dwExtraInf);
private void btnSet_Click(object sender, EventArgs e)
{
int x = Convert.ToInt16(txtX.Text);//set x position
int y = Convert.ToInt16(txtY.Text);//set y position
Cursor.Position = new Point(x, y);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//make left button down
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//make left button up
}
感谢JOHNYKUTTY提供的帮助。