最近項目組開發的一個小工具想要在右鍵菜單中添加打開方式,以有道雲筆記為例進行了需求拆解和代碼編寫
1.需求拆解:
如何實現手動添加右鍵菜單的打開方式:
Step1:打開注冊表編輯器,Win+R->輸入 “regedit”
Step2:在HKEY_CLASSES_ROOT/*/shell (或者HKEY_LOCAL_MACHINE/SOFTWARE/Classes/*/shell ,兩個目錄是一樣的) 添加一個key:YNote,然后在該項中新建項command,然后再編輯字符串,添加應用程序的路徑,最后再路徑和名稱的后面加上空格和“%1”,然后在右鍵就可以找到YNote的打開方式
2.代碼實現
Method1:通過_winreg模塊實現:

1 import _winreg 2 from _winreg import KEY_ALL_ACCESS 3 4 with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Classes\*\shell") as key: 5 print key 6 7 newKey = _winreg.CreateKeyEx(key,"YNote",0,KEY_ALL_ACCESS) 8 9 sub_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r"SOFTWARE\Classes\*\shell\YNote") 10 newsubKey = _winreg.CreateKey(sub_key,"command") 11 12 _winreg.SetValue(newsubKey,"(Default)",1,"\"C:\Program Files (x86)\Youdao\YoudaoNote\YoudaoNote.exe\" \"%1\"")
Method2:通過win32api和win32con模塊實現

1 import win32api 2 import win32con 3 4 key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,r"SOFTWARE\Classes\*\shell") 5 6 newKey = win32api.RegCreateKey(key,"YNote") 7 8 sub_key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,r"SOFTWARE\Classes\*\shell\YNote") 9 10 newsubKey = win32api.RegCreateKey(sub_key,"command") 11 12 win32api.RegSetValue(newsubKey,"(Default)", win32con.REG_SZ,"\"C:\Program Files (x86)\Youdao\YoudaoNote\YoudaoNote.exe\" \"%1\"")