微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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",winreg.REG_SZ,icon or '')
        with winreg.CreateKey(key,"command") as key2:
            winreg.SetValueEx(key2,"",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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐