参考链接:https://stackoverflow.com/questions/67711879/python-3-x-ctypes-windows-api-call-fails-with-error-bad-length-24
import ctypes
from ctypes import wintypes
ULONG_PTR = wintypes.LPARAM # ULONG_PTR type changes size 32-/64-bit. LPARAM does too.
MAX_PATH = 260 # Needed for "exe" array to define correctly
TH32CS_SNAPPROCESS = 0x00000002
ERROR_NO_MORE_FILES = 18
class PROCESSENTRY32(ctypes.Structure):
'''
DWORD dwSize;
DWORD cntUsage;
DWORD th32ProcessID;
ULONG_PTR th32DefaultHeapID;
DWORD th32ModuleID;
DWORD cntThreads;
DWORD th32ParentProcessID;
LONG pcPriClassBase;
DWORD dwFlags;
CHAR szExeFile[MAX_PATH];
'''
_fields_ = [("dwSize", wintypes.DWORD),
("cntUsage", wintypes.DWORD),
("th32ProcessID", wintypes.DWORD),
("th32DefaultHeapID", ULONG_PTR),
("th32ModuleID", wintypes.DWORD),
("cntThreads", wintypes.DWORD),
("th32ParentProcessID", wintypes.DWORD),
("pcPriClassBase", wintypes.LONG),
("dwFlags", wintypes.DWORD),
("szExeFile", wintypes.WCHAR * MAX_PATH)]
def getProcessList():
# Declaring parameter types and return values helps catch errors.
# HANDLE is different on 32-/64-bit as well and can get truncated.
kernel32dll = ctypes.windll.kernel32
kernel32dll.CreateToolhelp32Snapshot.argtypes = wintypes.DWORD, wintypes.DWORD
kernel32dll.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel32dll.Process32FirstW.argtypes = wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)
kernel32dll.Process32FirstW.restype = wintypes.BOOL
kernel32dll.Process32NextW.argtypes = wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)
kernel32dll.Process32NextW.restype = wintypes.BOOL
CreateToolhelp32Snapshot = kernel32dll.CreateToolhelp32Snapshot
Process32First = kernel32dll.Process32First
Process32Next = kernel32dll.Process32Next
Process32FirstW = kernel32dll.Process32FirstW
Process32NextW = kernel32dll.Process32NextW
CloseHandle = kernel32dll.CloseHandle
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
flag = Process32FirstW(hProcessSnap, pe32)
while flag:
print(pe32.szExeFile)
if Process32NextW(hProcessSnap, pe32) == False:
break
CloseHandle(hProcessSnap)
if __name__ == '__main__':
getProcessList()