winform如何获取鼠标在屏幕中的位置?
一、先进行如下定义及注册
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int x, int y);
//移动鼠标
const int MOUSEEVENTF_MOVE = 0x0001;
//模拟鼠标左键按下
const int MOUSEEVENTF_LEFTDOWN = 0x0002;
//模拟鼠标左键抬起
const int MOUSEEVENTF_LEFTUP = 0x0004;
//模拟鼠标右键按下
const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
//模拟鼠标右键抬起
const int MOUSEEVENTF_RIGHTUP = 0x0010;
//模拟鼠标中键按下
const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
//模拟鼠标中键抬起
const int MOUSEEVENTF_MIDDLEUP = 0x0040;
//标示是否采用绝对坐标
const int MOUSEEVENTF_ABSOLUTE = 0x8000;
//模拟鼠标滚轮滚动操作,必须配合dwData参数
const int MOUSEEVENTF_WHEEL = 0x0800;
二、再定义如下函数
private static void SetPosAndClickMouse(int x,int y) //设置鼠标位置并点击左键
{
int dx = x;
int dy = y;
SetCursorPos(dx, dy);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//
mouse_event((MOUSEEVENTF_LEFTUP), 0, 0, 0,0);
}
三、这样来调用
SetPosAndClickMouse(800, 600);
四、注意事项
为了能让窗体能够及时获取鼠标位置,最好在窗体加上timer1定时器来更新鼠标位置。
private void Form1_Load(object sender, EventArgs e) //启动timer
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e) //获取鼠标在屏幕中的位置
{
if (webBrowser1.Bounds.Contains(this.PointToClient(Cursor.Position)))
{
label1.Text = webBrowser1.PointToClient(Cursor.Position).ToString();
}
}