用管理员权限运行,重复执行会起到覆盖效果(根据sub_key)。
from winreg import *
registry = r"Directory\Background\Shell"
# Warning: 不要将sub_key改为cmd或PowerShell,否则可能会与系统已有项冲突。
config = [
{
"sub_key": "mouse_cmd",
"text": "Windows Command",
"icon": r"C:\Users\CF\Desktop\icon\cmd.ico",
"command": "cmd",
},
{
"sub_key": "mouse_cmd_admin",
"text": "Windows Command (管理员)",
"icon": r"C:\Users\CF\Desktop\icon\cmd.ico",
"command": "PowerShell -windowstyle Hidden -Command \"Start-Process cmd.exe -ArgumentList '/s,/k, pushd,%V' -Verb RunAs\"",
},
{
"sub_key": "mouse_PowerShell",
"text": "Windows PowerShell",
"icon": r"C:\Users\CF\Desktop\icon\powershell.ico",
"command": "PowerShell",
},
{
"sub_key": "mouse_PowerShell_admin",
"text": "Windows PowerShell (管理员)",
"icon": r"C:\Users\CF\Desktop\icon\powershell.ico",
"command": 'powershell -WindowStyle Hidden -NoProfile -Command "Start-Process -Verb RunAs powershell.exe -ArgumentList \\"-NoExit -Command Push-Location \\\\\\"\\"%V/\\\\\\"\\"\\"',
},
]
for item in config:
key = OpenKey(HKEY_CLASSES_ROOT, registry)
SetValue(key, item["sub_key"], REG_SZ, item["text"]) # 创建子键,并设置其默认项的值(提示文字)
key = OpenKey(
HKEY_CLASSES_ROOT, registry + "\\" + item["sub_key"], access=KEY_WRITE
) # 打开子键
SetValueEx(key, "icon", None, REG_SZ, item["icon"]) # 在子键中设置Icon项的值
SetValue(
key, "command", REG_SZ, item["command"]
) # 在子键中创健子键command,设置其默认项的值(command)
print("successfully")
想了解过程的可以看下下面的。
# function: add cmd.exe to right-click context menu
g_text = "命令提示符" # 显示文字
g_icon = r"C:\Users\CF\Pictures\Saved Pictures\cmd.ico" # 图标路径
g_exe = r"C:\Windows\system32\cmd.exe" # 可执行文件路径
g_key = r"right-click_cmd" # 自定义,注册表字段名,不要和已有的冲突
import winreg
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"Directory\Background\Shell")
winreg.SetValue(key, g_key, winreg.REG_SZ, g_text)
key = winreg.OpenKeyEx(
winreg.HKEY_CLASSES_ROOT,
r"Directory\Background\Shell\\" + g_key,
access=winreg.KEY_WRITE,
)
winreg.SetValueEx(key, "Icon", None, winreg.REG_SZ, g_icon)
winreg.SetValue(key, "command", winreg.REG_SZ, g_exe)
# 在用管理员权限时,方法是唤起一个PowerShell,然后Start-Process来发起一个管理员权限的进程;
# -verb Runas意思是管理员
# /s /k pushd %V大概是传递给cmd路径参数
# 示例:
# PowerShell -windowstyle hidden -Command "Start-Process cmd.exe -ArgumentList '/s,/k, pushd,%V' -Verb RunAs"