[英]How to add Python script to registry using Ctypes and kernel32.dll
我正在嘗試將我的程序添加到注冊表中,這是我的代碼...
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)
它沒有給我任何錯誤,但它仍然沒有在注冊表中創建一個新鍵。 我究竟做錯了什么?
要正確使用ctypes
,請定義.argtypes
和.restype
來對參數進行錯誤檢查。 許多使用的類型是錯誤的。 hkey
, hkey
、 flag
和samdesired
不是字符串。 返回值不是句柄,而是狀態。 返回值是一個輸出參數( pkhResult
中的pkhResult
)。 您必須閱讀文檔並仔細檢查所有變量定義的頭文件。
此外,在 Python 3 中字符串是 Unicode,因此使用W
形式的 Windows API 來接受 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.RegCreateKey
或win32api.RegCreateKeyEx
,其中所有工作都已為您完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.