要獲得當前窗口的句柄,可以使用以下步驟:
引入user32
庫:在代碼文件的開頭添加以下代碼:
import ctypes
from ctypes import wintypes
定義user32
庫中的函數和數據類型:
# 定義函數類型
EnumWindowsProc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
# 定義函數
user32 = ctypes.windll.user32
user32.EnumWindows.restype = wintypes.BOOL
user32.EnumWindows.argtypes = [EnumWindowsProc, wintypes.LPARAM]
user32.GetWindowThreadProcessId.restype = wintypes.DWORD
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
定義一個回調函數來處理每個窗口:
def enum_windows_callback(hwnd, lparam):
current_process_id = ctypes.c_ulong()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(current_process_id))
# 這里可以根據需要添加一些條件判斷
# 比如判斷窗口標題或窗口類名是否符合要求
# 輸出窗口句柄和進程ID
print(f"窗口句柄: {hwnd}, 進程ID: {current_process_id.value}")
return True
調用EnumWindows
函數,將回調函數傳遞給它:
user32.EnumWindows(EnumWindowsProc(enum_windows_callback), 0)
運行代碼后,將會輸出當前所有窗口的句柄和進程ID。根據需要,你可以在回調函數中添加一些條件判斷,以便過濾出你想要的窗口。