用代码控制鼠标键盘(C#语言)

时间:2022-04-21 06:00:35

前些时间想做一个鼠标点击器,用到了这些知识。

下面整理记录一下。

ps.感谢各位大神


下面直接上代码

1.鼠标的控制

class MouseMove
{
#region MouseEvent
[System.Runtime.InteropServices.DllImport("user32")]
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;
#endregion //x,y是鼠标在屏幕的位置,屏幕左上角为0,0点
public void MouseMoveAndClick(int _x, int _y)
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, _x * / screenWH.x, _y * / screenWH.y, , );
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, , , , );
}
}

ps.其他的单击双击什么的可以自己定义

2.键盘的控制

class KeyBordClick
{
[DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
private static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
const int KEYEVENTF_KEYUP = 0x02;
const int KEYEVENTF_KEYDOWN = 0x00; //相当于按下ctrl+v,然后回车
private void KeyBordPaste()
{
keybd_event(Keys.ControlKey, , KEYEVENTF_KEYDOWN, );
keybd_event(Keys.V, , , );
keybd_event(Keys.ControlKey, , KEYEVENTF_KEYUP, );
keybd_event(Keys.Enter, , , );
}
}

3.剪切板

使用Clipboard类

Clipboard. SetDataObject("HELLO WORLD!!!", true);

ps.

本来想用hook来捕获记录鼠标位置的,可惜技术不够,没搞成。

&中间有次点击时间间隔太小了,导致鼠标乱跳,关不掉程序,只能呵呵哒重启了(也许可以恶作剧一下),囧