溫馨提示×

windows怎么獲得當前窗口句柄

小億
159
2023-12-01 16:37:00
欄目: 智能運維

要獲得當前窗口的句柄,可以使用以下步驟:

  1. 引入user32庫:在代碼文件的開頭添加以下代碼:

    import ctypes
    from ctypes import wintypes
    
  2. 定義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)]
    
  3. 定義一個回調函數來處理每個窗口:

    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
    
  4. 調用EnumWindows函數,將回調函數傳遞給它:

    user32.EnumWindows(EnumWindowsProc(enum_windows_callback), 0)
    

運行代碼后,將會輸出當前所有窗口的句柄和進程ID。根據需要,你可以在回調函數中添加一些條件判斷,以便過濾出你想要的窗口。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女