您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用python3怎么注冊一個全局熱鍵,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
#!/usr/bin/env python3 import win32con import ctypes import ctypes.wintypes from threading import Thread,activeCount, enumerate from time import sleep,time class Hotkey(Thread): user32 = ctypes.windll.user32 hkey_list = {} hkey_flags = {} #按下 hkey_running = {} #啟停 _reg_list = {} #待注冊熱鍵信息 def regiskey(self, hwnd=None, flagid=0, fnkey=win32con.MOD_ALT, vkey=win32con.VK_F9): # 注冊熱鍵,默認一個alt+F9 return self.user32.RegisterHotKey(hwnd, flagid, fnkey, vkey) def get_reginfo(self): return self._reg_list def get_id(self,func): self_id = None for id in self.get_reginfo(): if self.get_reginfo()[id]["func"] == func: self_id = id break if self_id: self.hkey_running[self_id] = True return self_id def get_running_state(self,self_id): if self.hkey_running.get(self_id): return self.hkey_running[self_id] else: return False def reg(self,key,func,args=None): id = int(str(round(time()*10))[-6:]) fnkey = key[0] vkey = key[1] info = { "fnkey":fnkey, "vkey":vkey, "func":func, "args":args } self._reg_list[id] = info # print(info) #這里待注冊的信息 sleep(0.1) return id def fast_reg(self,id,key = (0,win32con.VK_HOME),func = lambda:print('熱鍵注冊開始')): if not self.regiskey(None, id, key[0], key[1]): print("熱鍵注冊失敗") return None self.hkey_list[id] = func self.hkey_flags[id] = False return id def callback(self): def inner(self = self): for flag in self.hkey_flags: self.hkey_flags[flag] = False while True: for id, func in self.hkey_list.items(): if self.hkey_flags[id]: args = self._reg_list[id]["args"] if args: # print(args) #這里打印傳入給注冊函數的參數 thread_it(func,*args) else: thread_it(func) self.hkey_flags[id] = False return inner def run(self): for id in self._reg_list: reg_info = self._reg_list[id] fnkey = reg_info["fnkey"] vkey = reg_info["vkey"] func = reg_info["func"] self.fast_reg(id,(fnkey, vkey), func) fn = self.callback() thread_it(fn) # 啟動監聽熱鍵按下線程 try: msg = ctypes.wintypes.MSG() while True: if self.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0: if msg.message == win32con.WM_HOTKEY: if msg.wParam in self.hkey_list: self.hkey_flags[msg.wParam] = True self.user32.TranslateMessage(ctypes.byref(msg)) self.user32.DispatchMessageA(ctypes.byref(msg)) finally: for id in self.hkey_list: self.user32.UnregisterHotKey(None, id) def thread_it(func, *args): t = Thread(target=func, args=args) t.setDaemon(True) t.start() def jump(func,hotkey): self_id = hotkey.get_id(func) while hotkey.get_running_state(self_id): print(f"{self_id : } 你正在1秒1次的跳動") sleep(1) def stop_jump(start_id,hotkey): hotkey.hkey_running[start_id] = False print(f"{start_id} 即將停止") sleep(1) print(f'當前線程列表:{activeCount()}', enumerate()) def main(): hotkey = Hotkey() start_id = hotkey.reg(key = (win32con.MOD_ALT,win32con.VK_HOME),func=jump,args=(jump,hotkey)) #alt home鍵 開始 hotkey.reg(key = (0,win32con.VK_END),func=stop_jump,args=(start_id,hotkey)) #alt end鍵 結束 hotkey.start() #啟動熱鍵主線程 print(f"當前總線程數量:{activeCount()}") print('當前線程列表:', enumerate()) print('熱鍵注冊初始化完畢,嘗試按組合鍵alt+Home 或者單鍵END看效果') if __name__ == '__main__': main()
以下是舊的代碼,用起來比較麻煩。
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ # File : demo.py # Author: DaShenHan&道長-----先苦后甜,任憑晚風拂柳顏------ # Date : 2019/6/28 import win32con import ctypes import ctypes.wintypes from threading import Thread, Timer, activeCount, enumerate from time import sleep h_ids = [i for i in range(2)] # 創建兩個熱鍵序列 h_keys = {i: False for i in h_ids} # 初始化所有熱鍵序列的標志符為False h_dict = {} # 初始化一個空的字典,記錄id與func class Hotkey(Thread): # 創建一個Thread的擴展類 user32 = ctypes.windll.user32 # 加載user32.dll # global h_ids, h_keys,h_dict def regiskey(self, hwnd=None, flagid=0, fnkey=win32con.MOD_ALT, vkey=win32con.VK_F9): # 注冊熱鍵,默認一個alt+F9 return self.user32.RegisterHotKey(hwnd, flagid, fnkey, vkey) def callback(self, id, func): h_dict[id] = func # 這個id對應這個func,沒有就是新增,有就是修改 def inner(): for key, value in h_dict.items(): print(f'總的熱鍵池:{h_ids},當前熱鍵序號:{key}, 當前熱鍵功能:{value},當前熱鍵狀態:{h_keys[h_ids[key]]}') while True: for key, value in h_dict.items(): if h_keys[h_ids[key]]: thread_it(value) # 另外開線程執行value h_keys[h_ids[key]] = False return inner def run(self): # print(self.user32) if not self.regiskey(None,h_ids[0],win32con.MOD_ALT,win32con.VK_F9): # 注冊快捷鍵alt+F9并判斷是否成功,該熱鍵用于執行一次需要執行的內容。 print(f"熱鍵注冊失敗! id{h_ids[0]}") # 返回一個錯誤信息 if not self.regiskey(None,h_ids[1],0,win32con.VK_F10): # 注冊快捷鍵F10并判斷是否成功,該熱鍵用于結束程序,且最好這么結束,否則影響下一次注冊熱鍵。 print(f"熱鍵注冊失敗! id{h_ids[1]}") # 以下為檢測熱鍵是否被按下,并在最后釋放快捷鍵 try: msg = ctypes.wintypes.MSG() while True: if self.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0: if msg.message == win32con.WM_HOTKEY: if msg.wParam in h_ids: h_keys[msg.wParam] = True self.user32.TranslateMessage(ctypes.byref(msg)) self.user32.DispatchMessageA(ctypes.byref(msg)) finally: for i in h_ids: self.user32.UnregisterHotKey(None, i) # 必須得釋放熱鍵,否則下次就會注冊失敗,所以當程序異常退出,沒有釋放熱鍵, # 那么下次很可能就沒辦法注冊成功了,這時可以換一個熱鍵測試 def thread_it(func, *args): t = Thread(target=func, args=args) t.setDaemon(True) t.start() def settimeout(func, sec): def inner(): func() Timer(sec, inner).start() thread_it(inner) def setinterval(func, sec, tmrname, flag=True): global timer_dict timer_dict[tmrname] = flag print("已設置tqtimer啟用狀態為:{}".format(flag)) def inner(): global timer_dict if timer_dict[tmrname]: func() Timer(sec, inner).start() thread_it(inner) def clearinterval(timername): global timer_dict timer_dict[timername] = False flag = timer_dict[timername] print("已設置tqtimer啟用狀態為:{}".format(flag)) def test_start(): print("按下了開始鍵...the programe is running") def test_stop(): print("按下了停止鍵...the programe is stopped") def run_ok(): hotkey = Hotkey() hotkey.start() fn = hotkey.callback(0, test_start) fn = hotkey.callback(1, test_stop) thread_it(fn) sleep(0.5) count = activeCount() print(f"當前總線程數量:{count}") print('當前線程列表:', enumerate()) print('熱鍵注冊初始化完畢,嘗試按組合鍵alt+F9 或者單鍵F10看效果') while True: pass if __name__ == '__main__': run_ok()
關于使用python3怎么注冊一個全局熱鍵就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。