C# 虚拟按键和模拟鼠标

        我们测试软件功能,有时候需要不停操作按键和鼠标。通过虚拟按键和模拟鼠标操作可以轻松完成重复而繁琐的操作,节省人工时间和人为失误。虚拟按键和模拟鼠标操作还可以实现对远程电脑的按键和鼠标操作,实现屏幕协助。

虚拟按键可通过Keybd_event实现

    public class Key
    {
        [DllImport("user32.dll")]
        public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        //按键按下
        private static readonly byte KEYEVENTF_KEYDOWN = 0x0000;
        //按键弹起
        private static readonly byte KEYEVENTF_KEYUP = 0x0002;

        public static readonly byte VK_Enter = 0x0D;

        public static void ClickKey(byte key)
        {
            keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0); 
            keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
        }
    }

    void Main()
    {
         //点击一下Enter键
         Key.ClickKey(Key.VK_Enter);
    }

模拟鼠标操作使用mouse_event函数

    public class Mouse
    {
        [DllImport("user32", CharSet = CharSet.Unicode)]
        private static extern int mouse_event(int dwFlags, int dx, int dy, int dwData, 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;

        [DllImport("User32.dll")]
        //读取光标位置
        public extern static bool GetCursorPos(ref Point pot);

        [DllImport("User32.dll")]
        //设置光标位置
        public extern static void SetCursorPos(int x, int y);

        //鼠标左键单击一次
        public static void LeftMouseClick()
        {
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }

        //鼠标右键键单击一次
        public static void RightMouseClick()
        {
            mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
        }
        //双击一次
        public static void DoubleLeftClick()
        {
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }
        //设置绝对路径点击一次
        public static void SetClickPosition(int x,int y)
        {
            mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
        }
    }

    void Main()
    {
         //横坐标x为200,纵坐标为500位置点击了一下,屏幕原点坐标为左上角
         Mouse.SetClickPosition(200, 500);
    }

 虚拟按键参考:

keybd_event 函数 (winuser.h) - Win32 apps | Microsoft Learn

​​​​​​Virtual-Key Codes (Winuser.h) - Win32 apps | Microsoft Learn

模拟鼠标参考:

mouse_event 函数 (winuser.h) - Win32 apps | Microsoft Learn

你可能感兴趣的:(WPF,C#,c#,开发语言)