C#使用mouse_event函数模拟鼠标事件
mouse_event函数
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);1、dwFlags代表鼠标动作;
2、dx代表横坐标,使用时需要加一个屏幕分辨率;
3、dy代表纵坐标,使用时需要加一个屏幕分辨率;
4、cButtons和dwExtraInfo使用时直接写0;
//导入user32.dll
[System.Runtime.InteropServices.DllImport("user32")]
//mouse_event函数:
//1、dwFlags代表鼠标动作;2、dx代表横坐标;3、dy代表纵坐标;4、cButtons和dwExtraInfo使用时直接写0;
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
//移动鼠标
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;
//鼠标移动(相对):相对于鼠标当前位置
private void MouseMove(int x, int y,int dpiX,int dpiY)
{
mouse_event(MOUSEEVENTF_MOVE, x * 65535 / dpiX, y * 65535 / dpiY, 0, 0);
}
//鼠标移动(绝对):相对于屏幕定点移动
private void MouseMoveIsAbsolute(int x,int y, int dpiX, int dpiY)
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x * 65535 / dpiX, y * 65535 / dpiY, 0, 0);
}
//鼠标左键点击
private void MouseClick_Left()
{
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
//鼠标右键点击
private void MouseClick_Right()
{
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
}
//鼠标中间点击
private void MouseClick_Mid()
{
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
}