keyboard_listener.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2022/10/05 06:19:13
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : 按键监听
  8. '''
  9. import keyboard
  10. import time
  11. from screen_shot import ScreenCapture
  12. import io
  13. class KeyboardListener:
  14. def __init__(self, tcpServer):
  15. self.tcpServer = tcpServer
  16. self.t = 0
  17. self.c = 0
  18. self.key_state_map = {}
  19. self.screen_capture = None
  20. def listen_keyboard(self, callback):
  21. self.callback = callback
  22. keyboard.hook(self.onKeyEvent)
  23. keyboard.wait()
  24. def onImgCapture(self, pic):
  25. imgByteArr = io.BytesIO()
  26. pic.save(imgByteArr, format='JPEG')
  27. bytes_data = imgByteArr.getvalue()
  28. self.tcpServer.send_img(bytes_data)
  29. def isCtrlHolding(self):
  30. return ('ctrl' in self.key_state_map and self.key_state_map['ctrl'] == 'down')\
  31. or ('left ctrl' in self.key_state_map and self.key_state_map['left ctrl'] == 'down')\
  32. or ('right ctrl' in self.key_state_map and self.key_state_map['right ctrl'] == 'down')
  33. def isAltHolding(self):
  34. return ('alt' in self.key_state_map and self.key_state_map['alt'] == 'down')\
  35. or ('left alt' in self.key_state_map and self.key_state_map['left alt'] == 'down')\
  36. or ('right alt' in self.key_state_map and self.key_state_map['right alt'] == 'down')
  37. def isKeyHolding(self, key):
  38. return (key in self.key_state_map and self.key_state_map[key] == 'down')
  39. def onKeyEvent(self, key):
  40. # update key_state_map
  41. self.key_state_map[key.name.lower()] = key.event_type
  42. # is screenshoot?
  43. if self.isKeyHolding("caps lock")\
  44. and key.event_type == "down"\
  45. and key.name.lower() == "a":
  46. self.screen_capture = ScreenCapture()
  47. self.screen_capture.are_capture(self.onImgCapture)
  48. print(self.key_state_map)
  49. # is triple c?
  50. if key.event_type == "down" \
  51. and key.name.lower() == "c" \
  52. and self.isCtrlHolding():
  53. if self.t == 0:
  54. self.t = time.time()
  55. self.c += 1
  56. print("wait for nex c", self.c)
  57. return
  58. if (time.time()-self.t < 0.5):
  59. self.t = time.time()
  60. self.c += 1
  61. print("wait for nex c:", self.c)
  62. else:
  63. self.c = 0
  64. self.t = 0
  65. print("wait for nex c", self.c)
  66. if self.c >= 2:
  67. self.c = 0
  68. print("need trans")
  69. if self.callback:
  70. self.callback()