Global hotkey on windows with tkinter

為{幸葍}努か 提交于 2021-02-04 21:11:39

问题


I want a python tkinter application to register a global hotkey (triggered even if the application has not the focus). I've found some pieces, but I can't find a way to put them together...

Basically, I can register the hotkey (with a call to the windows API RegisterHotKey), but it send a "WM_HOTKEY" message to the root windows that is under Tkinter mainloop management, and I cant find a way to bind on it...

tk.protocol() function seems to be there for it, but this message seems not to be understood (I can't find a complete list of the recognized messages)...

Here a non-working code example where I would like to print a message when "WIN-F3" is pressed...

import Tkinter
import ctypes
import win32con

class App(Tkinter.Tk): 
    def __init__(self):
        Tkinter.Tk.__init__(self)

        user32 = ctypes.windll.user32
        if user32.RegisterHotKey (None, 1, win32con.MOD_WIN , win32con.VK_F3):
            print("hotkey registered")
        else:
            print("Cannot register hotkey")

        self.protocol("WM_HOTKEY", self.hotkey_received)

    def hotkey_received(self):
        print("hotkey")

if __name__ == "__main__":
    app = App()
    app.mainloop()
    try:
        app.destroy()
    except:
        pass    

Thanks

EDIT --------------------------------

OK, I found a way by pushing the whole windows loop in a separate thread, independent from the tkinter mainloop.

It doesn't feel like a clean solution though as I have actually 2 loops running for basically the same kind of interactions with the OS, and it require a message queue to interact with the application, but it do the trick... If someone has a better option, I would be happy to see it...


回答1:


A little bit late but maybe it would be helpful for someone... Read this answer.



来源:https://stackoverflow.com/questions/20786933/global-hotkey-on-windows-with-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!