ウィンドウズで現在のアクティブなウィンドウのハンドルの取得方法

現在のウィンドウのハンドルを取得するには、次の手順を使用します。

  1. user32ライブラリのインポート: コードファイルの最初の行に以下のコードを追加します:
  2. import ctypes
    ctypesからwintypesをインポートします
  3. user32ライブラリの関数やデータ型の定義
  4. 関数型の定義
    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)]
  5. 各ウィンドウに対して処理を行うコールバック関数を定義します。
  6. 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

  7. コールバック関数を渡してEnumWindows関数を呼び出す
  8. user32.EnumWindows(user32.EnumWindowsProc(enum_windows_callback), 0)

コードを起動すると、全てのウィンドウのハンドルとプロセス ID が出力されます。必要に応じて、コールバック関数に条件判断を追加し、必要なウィンドウをフィルタリングできます。

bannerAds