windows下python管理右键菜单

实现很简单,不记得什么时候写的了,贴出来希望能有所价值

"""
Windows中创建右键菜单
"""
import os
import sys
import winreg
import ctypes


def is_user_admin():
    """ 检查admin """
    return ctypes.windll.shell32.IsUserAnAdmin()


def run_as_admin():
    """ 管理员运行 """
    script = os.path.abspath(sys.argv[0])
    args = ' '.join(sys.argv[1:]) if len(sys.argv) > 1 else ''
    from win32com.shell.shell import ShellExecuteEx
    ShellExecuteEx(lpFile=sys.executable, lpParameters=f"{script} {args}",
                   nShow=1, lpVerb='runas')
    return


def create_right_menu(name, icon, command):
    """ 创建右键菜单 """
    key_root = winreg.HKEY_CLASSES_ROOT
    key_path = fr"Directory\Background\shell\{name}"
    with winreg.CreateKey(key_root, key_path) as key:
        winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, icon or '')
        with winreg.CreateKey(key, "command") as key2:
            winreg.SetValueEx(key2, "", 0, winreg.REG_SZ, command or '')


def remove_right_menu(name):
    """删除右键菜单"""
    """
    // from winreg.h
    #define HKEY_CLASSES_ROOT                   (( HKEY ) (ULONG_PTR)((LONG)0x80000000) )
    #define HKEY_CURRENT_USER                   (( HKEY ) (ULONG_PTR)((LONG)0x80000001) )
    #define HKEY_LOCAL_MACHINE                  (( HKEY ) (ULONG_PTR)((LONG)0x80000002) )
    #define HKEY_USERS                          (( HKEY ) (ULONG_PTR)((LONG)0x80000003) )
    #define HKEY_PERFORMANCE_DATA               (( HKEY ) (ULONG_PTR)((LONG)0x80000004) )
    #define HKEY_PERFORMANCE_TEXT               (( HKEY ) (ULONG_PTR)((LONG)0x80000050) )
    #define HKEY_PERFORMANCE_NLSTEXT            (( HKEY ) (ULONG_PTR)((LONG)0x80000060) )
    #if (WINVER >= 0x0400)
    #define HKEY_CURRENT_CONFIG                 (( HKEY ) (ULONG_PTR)((LONG)0x80000005) )
    #define HKEY_DYN_DATA                       (( HKEY ) (ULONG_PTR)((LONG)0x80000006) )
    #define HKEY_CURRENT_USER_LOCAL_SETTINGS    (( HKEY ) (ULONG_PTR)((LONG)0x80000007) )
    """
    key_root = 0x80000000  # winreg.HKEY_CLASSES_ROOT
    key_path = fr"Directory\Background\shell\{name}"
    ctypes.windll.Advapi32.RegDeleteTreeW(key_root, key_path)


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("name", type=str, help="Name.")
    parser.add_argument("-i", "--icon", help="Icon.")
    parser.add_argument("-c", "--command", help="Command.")
    parser.add_argument("-r", "--remove", action="store_true",
                        help="Remove with name.")
    args = parser.parse_args()

    if not is_user_admin():
        run_as_admin()
        return

    try:
        if args.remove:
            remove_right_menu(args.name)
            return

        create_right_menu(args.name, args.icon, args.command)
    except Exception as ex:
        print(ex)
        os.system('pause')


if __name__ == '__main__':
    main()