I’m capturing keyboard events for a remote desktop application by overriding the keyPressEvent() function like this:
def keyPressEvent(self, event):
key = event.key()
if key > 9999999999:
print('key code too long')
return
self.io_soc.send(f'key {key}'.encode()
I want to simulate the keyboard event on the other computer, but the problem is that the I need to convert the key code that event.key() gives to a string because pyautogui.press() takes a string as an argument.
I didn’t find any way to get the key as a string or convert it. Please provide me with a way to do this conversion, or a way to solve this problem
>Solution :
Ok, try this:
from PyQt5.QtCore import Qt
# Dictionary mapping Qt key codes to pyautogui string representations
KEY_MAP = {
Qt.Key_Backspace: 'backspace',
Qt.Key_Tab: 'tab',
# Add mappings for other keys you need to support
Qt.Key_Return: 'enter',
Qt.Key_Enter: 'enter',
Qt.Key_Escape: 'esc',
Qt.Key_Space: 'space',
Qt.Key_End: 'end',
Qt.Key_Home: 'home',
Qt.Key_Left: 'left',
Qt.Key_Up: 'up',
Qt.Key_Right: 'right',
Qt.Key_Down: 'down',
Qt.Key_Delete: 'delete',
# ... and so on for other non-character keys
}
class RemoteDesktopWidget(QWidget):
# ... other methods ...
def keyPressEvent(self, event):
key = event.key()
if key > 9999999999:
print('key code too long')
return
# Check if key is a known special key
if key in KEY_MAP:
key_str = KEY_MAP[key]
else:
# Convert to a string representation for character keys
key_str = event.text()
self.io_soc.send(f'key {key_str}'.encode())