Listening to keyboard events without trapping them?

后端 未结 4 1702
别跟我提以往
别跟我提以往 2021-02-05 14:03

I\'m writing an command-line application which listens for Control key release events in X Windows and alerts another process when it detects them.

Being new to GNU/Linu

相关标签:
4条回答
  • 2021-02-05 14:15

    You need to use the XRecord extension. It can be used with pyxlib (pykeylogger mentioned in the other answer uses this), or by wrapping libX11 and libXtst via ctypes (as I did in synaptiks).

    Note however, that programming with xrecord (and to some degree also with XLib in general) is somehwat hard, because the API is badly documented, and quite baroque and counter-intuitive.

    0 讨论(0)
  • 2021-02-05 14:28

    Thanks to the pykeylogger library mentioned by Croad Langshan, and to the helpful example code provided by Tim Alexander, the author of such library, I've been able to change my program to:

        #!/usr/bin/env python
    
        from pyxhook import HookManager
    
        watched_keys = ["Control_R", "Control_L"]
    
        def handle_event (event):
            if event.Key in watched_keys:
                print "KeyRelease"
    
    
        hm = HookManager()
        hm.HookKeyboard()
        hm.KeyUp = handle_event
        hm.start()
    

    This program accomplishes my goal without any issue. You can read the fields of the "event" object for further information about the event (see source code of "pyxhook.py").

    0 讨论(0)
  • 2021-02-05 14:30

    Note that the XRecord extension continues to be broken in a few distributions. The reason I hadn't gone back and updated that library for a while was because it was broken in Ubuntu for multiple releases. There's a way to do it as well with an XInput overlay, (I'm told) but I never pursued that because I didn't want to deal with an overlay rather than hooking the X events directly.

    Comment back if there's any issues with using the code in the pyxhook lib, I tried to make it as simple/robust as possible, but I may have missed stuff when putting it together. It was a while ago.

    0 讨论(0)
  • 2021-02-05 14:37

    Presumably this project must have code that solves that problem:

    http://sourceforge.net/apps/mediawiki/pykeylogger/index.php?title=Main_Page

    0 讨论(0)
提交回复
热议问题