python键盘、鼠标控制

本文介绍如何使用PyHook模块实现Python中的键盘和鼠标事件监听。通过示例代码展示了如何捕获并记录键盘按键和鼠标移动事件,适用于行为监控或自动化测试场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python键盘、鼠标控制
使用pyhook模块可以很快地完成键盘及鼠标事件捕获。 网站上提供了个使用的例子,改写了下,将信息记录到文件中,本来想使用python的logging模块,但测试时发现,因为鼠标事件频率太高,导致写时报I/O错误的异常,所以使用了自己写文件记录日志的方式。
代码:
Python代码
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-


  3. import pythoncom
  4. import pyHook
  5. import time


  6. def onMouseEvent(event):
  7.     "处理鼠标事件"
  8.     fobj.writelines('-' * 20 + 'MouseEvent Begin' + '-' * 20 + '\n')
  9.     fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  10.     fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  11.     fobj.writelines("Message:%d\n" % event.Message)
  12.     fobj.writelines("Time_sec:%d\n" % event.Time)
  13.     fobj.writelines("Window:%s\n" % str(event.Window))
  14.     fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  15.     fobj.writelines("Position:%s\n" % str(event.Position))
  16.     fobj.writelines('-' * 20 + 'MouseEvent End' + '-' * 20 + '\n')
  17.     return True


  18. def onKeyboardEvent(event):
  19.     "处理键盘事件"
  20.     fobj.writelines('-' * 20 + 'Keyboard Begin' + '-' * 20 + '\n')
  21.     fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  22.     fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  23.     fobj.writelines("Message:%d\n" % event.Message)
  24.     fobj.writelines("Time:%d\n" % event.Time)
  25.     fobj.writelines("Window:%s\n" % str(event.Window))
  26.     fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  27.     fobj.writelines("Ascii_code: %d\n" % event.Ascii)
  28.     fobj.writelines("Ascii_char:%s\n" % chr(event.Ascii))
  29.     fobj.writelines("Key:%s\n" % str(event.Key))
  30.     fobj.writelines('-' * 20 + 'Keyboard End' + '-' * 20 + '\n')
  31.     return True




  32. if __name__ == "__main__":
  33.     '''
  34.     Function:操作SQLITE3数据库函数
  35.     Input:NONE
  36.     Output: NONE
  37.     author: socrates
  38.     blog:http://blog.youkuaiyun.com/dyx1024
  39.     date:2012-03-1
  40.     '''

  41.     #打开日志文件
  42.     file_name = "D:\\hook_log.txt"
  43.     fobj = open(file_name,  'w')


  44.     #创建hook句柄
  45.     hm = pyHook.HookManager()


  46.     #监控键盘
  47.     hm.KeyDown = onKeyboardEvent
  48.     hm.HookKeyboard()


  49.     #监控鼠标
  50.     hm.MouseAll = onMouseEvent
  51.     hm.HookMouse()

  52.     #循环获取消息

  53.     #关闭日志文件
  54.     fobj.close()

复制代码
测试:
Plain 代码
  1. --------------------Keyboard Begin--------------------
  2. Current Time:Thu, 01 Mar 2012 15:07:01
  3. MessageName:key down
  4. Message:256
  5. Time:6376015
  6. Window:66926
  7. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  8. Ascii_code: 103
  9. Ascii_char:g
  10. Key:G
  11. --------------------Keyboard End--------------------
  12. --------------------MouseEvent Begin--------------------
  13. Current Time:Thu, 01 Mar 2012 15:07:01
  14. MessageName:mouse move
  15. Message:512
  16. Time_sec:6376078
  17. Window:132584
  18. WindowName:None
  19. Position:(724, 344)
  20. --------------------MouseEvent End--------------------
  21. --------------------MouseEvent Begin--------------------
  22. Current Time:Thu, 01 Mar 2012 15:07:01
  23. MessageName:mouse move
  24. Message:512
  25. Time_sec:6376109
  26. Window:132584
  27. WindowName:None
  28. Position:(724, 344)
  29. --------------------MouseEvent End--------------------
  30. --------------------Keyboard Begin--------------------
  31. Current Time:Thu, 01 Mar 2012 15:07:01
  32. MessageName:key down
  33. Message:256
  34. Time:6376625
  35. Window:66926
  36. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  37. Ascii_code: 111
  38. Ascii_char:o
  39. Key:O
  40. --------------------Keyboard End--------------------
  41. --------------------Keyboard Begin--------------------
  42. Current Time:Thu, 01 Mar 2012 15:07:02
  43. MessageName:key down
  44. Message:256
  45. Time:6376781
  46. Window:66926
  47. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  48. Ascii_code: 111
  49. Ascii_char:o
  50. Key:O
  51. --------------------Keyboard End--------------------
  52. --------------------Keyboard Begin--------------------
  53. Current Time:Thu, 01 Mar 2012 15:07:02
  54. MessageName:key down
  55. Message:256
  56. Time:6377000
  57. Window:66926
  58. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  59. Ascii_code: 103
  60. Ascii_char:g
  61. Key:G
  62. --------------------Keyboard End--------------------
  63. --------------------Keyboard Begin--------------------
  64. Current Time:Thu, 01 Mar 2012 15:07:02
  65. MessageName:key down
  66. Message:256
  67. Time:6377140
  68. Window:66926
  69. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  70. Ascii_code: 108
  71. Ascii_char:l
  72. Key:L
  73. --------------------Keyboard End--------------------
  74. --------------------Keyboard Begin--------------------
  75. Current Time:Thu, 01 Mar 2012 15:07:02
  76. MessageName:key down
  77. Message:256
  78. Time:6377187
  79. Window:66926
  80. WindowName:淘宝网 - 淘我喜欢! - Windows Internet Explorer
  81. Ascii_code: 101
  82. Ascii_char:e
  83. Key:E
  84. --------------------Keyboard End--------------------
  85. --------------------MouseEvent Begin--------------------
  86. Current Time:Thu, 01 Mar 2012 15:07:07
  87. MessageName:mouse move
  88. Message:512
  89. Time_sec:6382093
  90. Window:132584
  91. WindowName:None
  92. Position:(725, 344)
  93. --------------------MouseEvent End--------------------


复制代码
由上面的记录可以看出,当时我通过IE上淘宝,并且输入了google这个单词,有可能这是商品名,用户名,或者密码,呵呵。
查看Ascii_char字段即可看出输入的字母。如果没有解析出来,可通过Ascii_code字段的值到ASCII表中查找即可
### Python 中使用 `pynput` 实现键盘鼠标控制 #### 使用 `pynput.mouse` 进行鼠标操作 通过 `pynput.mouse` 可以轻松实现鼠标的点击、移动以及滚动等功能。以下是具体方法: - **模拟鼠标点击** ```python from pynput.mouse import Button, Controller mouse = Controller() # 移动到指定位置 (x=100, y=200) mouse.position = (100, 200) # 单击左键 mouse.click(Button.left, 1) # 按住右键并释放 with mouse.pressed(Button.right): pass ``` 上述代码展示了如何设置鼠标的位置,并执行单击或按压按钮的操作[^1]。 - **监听鼠标事件** 可以利用 `Listener` 来捕获用户的鼠标活动,例如移动、点击或者滚轮动作。 ```python from pynput.mouse import Listener def on_click(x, y, button, pressed): if pressed: print(f'Mouse clicked at ({x}, {y}) with {button}') def on_scroll(x, y, dx, dy): print(f'Mouse scrolled at ({x}, {y}) by ({dx}, {dy})') with Listener(on_click=on_click, on_scroll=on_scroll) as listener: listener.join() ``` 此部分实现了当检测到特定行为时触发回调函数的功能[^4]。 #### 使用 `pynput.keyboard` 处理键盘输入 对于键盘交互而言,同样分为两大部分——发送按键指令与捕捉用户敲打的动作。 - **模拟按键序列** 下面的例子说明了怎样组合多个按键形成复合命令(比如 Ctrl+C),甚至还能保持某些修饰符处于激活状态一段时间。 ```python from pynput.keyboard import Key, Controller keyboard = Controller() # Press and release space keyboard.press(Key.space) keyboard.release(Key.space) # Type a lower case A; this will work even without holding Shift key explicitly. keyboard.tap('a') # Simultaneously press 'Shift'+'A', which produces an uppercase letter due to shift being held down during typing of 'A'. with keyboard.pressed(Key.shift): keyboard.tap('a') # Perform copy operation via shortcut keys combination i.e., Control + C keyboard.hotkey('ctrl', 'c') ``` 这些片段解释了基本字符录入之外更高级别的功能像热键绑定等[^2]。 - **监控键盘动态变化** 最后一点就是关于实时跟踪当前设备上发生的任何按键相关的事情。 ```python from pynput.keyboard import Listener def on_press(key): try: print(f'alphanumeric key {key.char} pressed') except AttributeError: print(f'special key {key} pressed') def on_release(key): print('{0} released'.format(key)) if key == Key.esc: # Stop listener when ESC is hit return False with Listener(on_press=on_press, on_release=on_release) as listener: listener.join() ``` 这里定义了一个简单的框架用于打印每次按下及松开某个键的信息直到按下ESC为止才会退出循环[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值