C# API Keybd_event + mouse_event 利用API程序控制按下某键

来源:互联网 发布:淘宝松本清优惠券 编辑:程序博客网 时间:2024/06/14 23:31

首先引入名称空间System.Runtime.InteropServices用来导入Windows DLL.

下面是实现代码:

[DllImport("user32.dll", EntryPoint = "mouse_event")]
        
public static extern void mouse_event(
            
int dwFlags,
            
int dx,
            
int dy,
            
int cButtons,
            
int dwExtraInfo
        );

        [DllImport(
"user32.dll", EntryPoint = "keybd_event")]
        
public static extern void keybd_event(
            
byte bVk,
            
byte bScan,
            
int dwFlags,
            
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//标示是否采用绝对坐标



        
public Form1()
        {
            InitializeComponent();

            
int X = 100;
            
int Y = 100;

            mouse_event( MOUSEEVENTF_RIGHTDOWN, X , Y , 
00);
            mouse_event(MOUSEEVENTF_RIGHTUP, X , Y, 
00);

            X 
+= 10;
            Y 
+= 65;
            mouse_event(MOUSEEVENTF_MOVE, X, Y , 
00);
            mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y , 
00);
            mouse_event(MOUSEEVENTF_LEFTUP, X, Y , 
00);

            keybd_event(
65000);//a
            keybd_event(66010);//b
            keybd_event(13000);//回车

        }

 

            keybd_event((byte)Keys.F11, 0, 0, 0);//按下F11
            keybd_event((byte)Keys.F11, 0, 0x2, 0);   //弹起F11

原创粉丝点击