当前位置:   article > 正文

C# 虚拟按键和模拟鼠标_c# 模拟鼠标键盘

c# 模拟鼠标键盘

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

虚拟按键可通过Keybd_event实现

  1. public class Key
  2. {
  3. [DllImport("user32.dll")]
  4. public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
  5. //按键按下
  6. private static readonly byte KEYEVENTF_KEYDOWN = 0x0000;
  7. //按键弹起
  8. private static readonly byte KEYEVENTF_KEYUP = 0x0002;
  9. public static readonly byte VK_Enter = 0x0D;
  10. public static void ClickKey(byte key)
  11. {
  12. keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);
  13. keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
  14. }
  15. }
  16. void Main()
  17. {
  18. //点击一下Enter键
  19. Key.ClickKey(Key.VK_Enter);
  20. }

模拟鼠标操作使用mouse_event函数

  1. public class Mouse
  2. {
  3. [DllImport("user32", CharSet = CharSet.Unicode)]
  4. private static extern int mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
  5. //移动鼠标
  6. const int MOUSEEVENTF_MOVE = 0x0001;
  7. //模拟鼠标左键按下
  8. const int MOUSEEVENTF_LEFTDOWN = 0x0002;
  9. //模拟鼠标左键抬起
  10. const int MOUSEEVENTF_LEFTUP = 0x0004;
  11. //模拟鼠标右键按下
  12. const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
  13. //模拟鼠标右键抬起
  14. const int MOUSEEVENTF_RIGHTUP = 0x0010;
  15. //模拟鼠标中键按下
  16. const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
  17. //模拟鼠标中键抬起
  18. const int MOUSEEVENTF_MIDDLEUP = 0x0040;
  19. //标示是否采用绝对坐标
  20. const int MOUSEEVENTF_ABSOLUTE = 0x8000;
  21. [DllImport("User32.dll")]
  22. //读取光标位置
  23. public extern static bool GetCursorPos(ref Point pot);
  24. [DllImport("User32.dll")]
  25. //设置光标位置
  26. public extern static void SetCursorPos(int x, int y);
  27. //鼠标左键单击一次
  28. public static void LeftMouseClick()
  29. {
  30. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
  31. }
  32. //鼠标右键键单击一次
  33. public static void RightMouseClick()
  34. {
  35. mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
  36. }
  37. //双击一次
  38. public static void DoubleLeftClick()
  39. {
  40. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
  41. mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
  42. }
  43. //设置绝对路径点击一次
  44. public static void SetClickPosition(int x,int y)
  45. {
  46. mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
  47. }
  48. }
  49. void Main()
  50. {
  51. //横坐标x为200,纵坐标为500位置点击了一下,屏幕原点坐标为左上角
  52. Mouse.SetClickPosition(200, 500);
  53. }

 虚拟按键参考:

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/272528
推荐阅读
相关标签
  

闽ICP备14008679号