Comparing KeyCode.vk to Virtual Key Codes in pynput.keyboard

82 views Asked by At

I’m working with the pynput.keyboard module in Python and I’m trying to detect when a specific key is pressed. In this case, I’m interested in the Shift key.

Here’s the code I’m using:

from pynput.keyboard import KeyCode, Listener

# Take hexadecimal input as a string
hex_input = input("Enter a hexadecimal number: ")

# Convert hexadecimal to integer
int_input = int(hex_input, 16)

def on_press(key):
  current_vk = KeyCode(key).vk
  target_vk = KeyCode.from_vk(int_input)
  print(f"current_vk = {current_vk} | target_vk = {target_vk}")
   
  # If the key pressed matches the integer input, stop the listener
  if current_vk == target_vk:
    print("The key is equal")
    return False

listener = Listener(on_press=on_press)
listener.start()
listener.join()

When I input 0x10 (which corresponds to the Shift key according to the Microsoft Virtual Key Codes), I expect the output to be “The key is equal” when I press the Shift key. However, it seemed like I was doing something wrong while converting.

Now: 
Enter a hexadecimal number: 0x10
current_vk = Key.shift | target_vk = <16>

What I want to achieve: 
Enter a hexadecimal number: 0x10
current_vk = <16> | target_vk = <16>
The key is equal

how can I fix the code?

0

There are 0 answers