以下のサンプルは,「ウィンドウタイトル」で特定のウィンドウを探し,そのウィンドウおよび子ウィンドウ(Static,Edit,ListBox など標準コントロール)に表示されているテキストを取得して,ファイルに書き出す Python スクリプトです。
(Windows 専用。Windows API を直接叩くため,pywin32 が必要です)
事前準備
pip install pywin32
スクリプト例
# -*- coding: utf-8 -*-
"""
指定したウィンドウに表示されているテキストをすべて取得して
テキストファイルに保存するスクリプト
Usage:
python dump_window_text.py "メモ帳" output.txt
"""
import sys
import ctypes
from ctypes import wintypes
import win32gui
import win32con
WM_GETTEXTLENGTH = win32con.WM_GETTEXTLENGTH
WM_GETTEXT = win32con.WM_GETTEXT
def get_text_from_hwnd(hwnd: int) -> str:
"""
1 つのウィンドウハンドル (HWND) に対して
WM_GETTEXT を送り,テキストを取得する
"""
# 取り出せる文字数を問い合わせ
length = win32gui.SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0)
if length == 0:
return ""
# 受け取りバッファを作成(+1 はヌル終端分)
buffer = ctypes.create_unicode_buffer(length + 1)
win32gui.SendMessage(hwnd, WM_GETTEXT, length + 1, ctypes.byref(buffer))
return buffer.value
def enum_all_children(parent_hwnd: int) -> list[int]:
"""
親ウィンドウ以下のすべての子ウィンドウ HWND を再帰的に列挙
"""
child_hwnds: list[int] = []
def _enum_child_proc(hwnd, lparam):
child_hwnds.append(hwnd)
return True # 続行
# 1 階層目
win32gui.EnumChildWindows(parent_hwnd, _enum_child_proc, None)
# 再帰的に深掘り
for child in child_hwnds.copy():
child_hwnds.extend(enum_all_children(child))
# 重複除外
return list(dict.fromkeys(child_hwnds))
def collect_window_text(target_title: str) -> dict[int, str]:
"""
ウィンドウタイトルに一致するトップレベルウィンドウを探し
そこにぶら下がる全 HWND のテキストを取得して辞書で返す
{hwnd: "text"}
"""
hwnd = win32gui.FindWindow(None, target_title)
if not hwnd:
raise RuntimeError(f"タイトル '{target_title}' のウィンドウが見つかりません")
# 対象ウィンドウ自身 + そのすべての子
hwnds = [hwnd] + enum_all_children(hwnd)
texts: dict[int, str] = {}
for h in hwnds:
text = get_text_from_hwnd(h)
if text: # 空文字は無視
texts[h] = text
return texts
def main():
if len(sys.argv) != 3:
print("Usage: python dump_window_text.py <WindowTitle> <OutputFile>")
sys.exit(1)
window_title = sys.argv[1]
out_file = sys.argv[2]
try:
texts = collect_window_text(window_title)
except RuntimeError as e:
print(e)
sys.exit(1)
# ファイル書き出し
with open(out_file, "w", encoding="utf-8") as f:
for hwnd, text in texts.items():
f.write(f"[HWND: 0x{hwnd:08X}]\n{text}\n\n")
print(f"完了: {len(texts)} 件のテキストを '{out_file}' に保存しました。")
if __name__ == "__main__":
main()
使い方
- 取得したいウィンドウをあらかじめ開いた状態にしておく
- コマンドプロンプト (PowerShell) から実行
python dump_window_text.py "メモ帳 - 無題" memo.txt
- 成功すると
memo.txt にテキストが保存されます
仕組みメモ
・FindWindow … タイトル文字列でトップレベルウィンドウのハンドルを取得
・EnumChildWindows … 直下の子ウィンドウ列挙
・WM_GETTEXTLENGTH / WM_GETTEXT … 各コントロールにメッセージを送ってテキストを取り出す
(Edit, Static, Button, ListBox, ComboBox など標準コントロールが対象)
注意点
- オーナードロー/カスタム描画されているウィンドウや,
ブラウザ・Electron アプリなどは WM_GETTEXT で中身を取得できません。
→ その場合は Microsoft UI Automation(pywinauto, comtypes など)を検討してください。
- 管理者権限が必要なアプリ(UAC で昇格したプロセス)を読むには,
スクリプトも同じ権限レベルで実行する必要があります。
- 取得したテキストに個人情報や機密情報が含まれる場合は,
取り扱い・保存に十分ご注意ください。