LoginSignup
2
1

More than 1 year has passed since last update.

python で別のアプリのウィンドウハンドルを取得

Posted at

何かしら windows の作業を自動化をするときは、特定のアプリのウィンドウだけ扱うことが少なくない。ウィンドウ操作について最小限のコードをメモしておく。


方法2つ記載する
・外部アプリを開始してそのウィンドウハンドルを取得
・既に起動しているアプリのウィンドウハンドルを取得

( 「# %%」の行は jupyter notebook 形式のセル区切りに相当します)

window_test
# %%
import subprocess
import time
import pyautogui

import win32gui
import win32con
import win32process

# %%
# プロセスIDからウィンドウハンドルを取得する関数
def get_hwnds_from_pid(pid):
    def callback(hwnd, hwnds):
        if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
            _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
            if found_pid == pid:
                hwnds.append(hwnd)
        return True

    hwnds = []
    win32gui.EnumWindows(callback, hwnds)
    return hwnds


# %%
# メモ帳を実行&ウィンドウハンドル取得する例
process = subprocess.Popen([r"notepad.exe"])
time.sleep (0.1)
hwnds = get_hwnds_from_pid(process.pid)
print(hwnds[0])
# 1638968

# %%
# 既に開いているメモ帳のウィンドウハンドル取得する例
hwnd = win32gui.FindWindow(None, "無題 - メモ帳")
print(hwnd)
# 1638968

# %%
# ウィンドウを常に最前面にする
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

・win32gui, win32con, win32process は C:\Windows\System32\user32.dll のラッパーみたいなものと考えている。
https://www.tokovalue.jp/API_INDEX_F.htm でできることを確認したら、win32gui ではどんなコマンドになっているか探す感じでいろいろできると思われる。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1