如何使用Ctypes和kernel32.dll将Python脚本添加到注册表

2024-10-02 02:41:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的程序添加到注册表,这是我的代码

def regc():
reg = windll.kernel32
print(reg)
hkey = 'HKEY_CURRENT_USER'
lsubkey = 'Software\Microsoft\Windows\CurrentVersion\Run'
reserved = 0
flag = 'REG_OPTION_BACKUP_RESTORE'
samdesired = 'KEY_ALL_ACCESS'
ipsec = None
handle = reg.RegCreateKeyExA(hkey, lsubkey, reserved, flag, samdesired, ipsec, None)

它没有给我任何错误,但它仍然没有在注册表中创建新的项。我做错了什么


Tags: 代码程序none注册表defregflagreserved
1条回答
网友
1楼 · 发布于 2024-10-02 02:41:15

要正确使用ctypes,请定义.argtypes.restype对参数进行错误检查。使用的许多类型都是错误的^例如,{}、flagsamdesired不是字符串。返回值不是句柄,而是状态。返回值是一个输出参数(pkhResult在文档中)。您必须仔细阅读文档并检查所有变量定义的头文件

另外,在Python 3中,字符串是Unicode的,因此使用Windows API的W形式来接受Unicode字符串。对子键使用原始字符串(r'...'),因为它包含可以解释为转义码的反斜杠

下面是一个工作示例:

from ctypes import *
from ctypes import wintypes as w

# Values found from reading RegCreateKeyExW documentation,
# using Go To Definition on the types in Visual Studio,
# and printing constants in a C program, e.g. printf("%lx\n",KEY_ALL_ACCESS);

HKEY = c_void_p
PHKEY = POINTER(HKEY)
REGSAM = w.DWORD
LPSECURITY_ATTRIBUTES = c_void_p
LSTATUS = w.LONG

# Disposition values
REG_CREATED_NEW_KEY = 0x00000001
REG_OPENED_EXISTING_KEY = 0x00000002

ERROR_SUCCESS = 0

HKEY_CURRENT_USER = c_void_p(0x80000001)
REG_OPTION_NON_VOLATILE = 0
KEY_ALL_ACCESS = 0x000F003F

dll = WinDLL('kernel32')
dll.RegCreateKeyExW.argtypes = HKEY,w.LPCWSTR,w.DWORD,w.LPWSTR,w.DWORD,REGSAM,LPSECURITY_ATTRIBUTES,PHKEY,w.LPDWORD
dll.RegCreateKeyExW.restype = LSTATUS

hkey = HKEY_CURRENT_USER
lsubkey = r'Software\Microsoft\Windows\CurrentVersion\Run'
options = REG_OPTION_NON_VOLATILE
samdesired = KEY_ALL_ACCESS

# Storage for output parameters...pass by reference.
handle = HKEY()
disp = w.DWORD()

status = dll.RegCreateKeyExW(HKEY_CURRENT_USER, lsubkey, 0, None, options, samdesired, None, byref(handle), byref(disp))
if status == ERROR_SUCCESS:
    print(f'{disp=} {handle=}')

输出:

disp=c_ulong(2) handle=c_void_p(3460)

处置值2表示密钥已存在(REG_OPENED_EXISTING_KEY

您还可以安装pywin32并在所有工作已经完成的地方使用win32api.RegCreateKeywin32api.RegCreateKeyEx

相关问题 更多 >

    热门问题