Search code examples
pythonpopupkeypressmsvcrt

Python (3.6.1) keypress detection and popups


Im kinda new to python and i tried printing the key when pressed on windows and show the key in a popup message:

import msvcrt
import ctypes  # An included library with Python install.

def Mbox(title, text, style):
    ctypes.windll.user32.MessageBoxW(0, text, title, style)

while True:
    if msvcrt.kbhit()== True:
        key = msvcrt.getch()
        print(key)  # just to show the result
        Mbox(key, key, 1)

And the problems are:

1) The output if i press a key is diffrent, for example :"A" is "b'A'" why? and how can i change it to only "A"? (the output on the popup is even weirder like : 1X when i press 1 or 2*x when i press 2)

2) Is While True: makes the code run all the time, and by that keeps it detecting if a key has been pressed?

3) Is there any lib for python which detects a key-press for windows and Linux altogether?


Solution

  • Ok I found some answers:

    1) msvcrt.getwch() Wide char variant of getch(), returning a Unicode value.

    Read more at: https://docs.python.org/3.6/library/msvcrt.html

    2) I Guess yes, if someone can confirm it ill be glad.

    3) Not that i know, there are diff libs for each op system (again if im wrong please leave a note here).