NotePad 視窗句柄 (HWND) 未正確取得。程式可能在檔案載入後、視窗標題改變前嘗試 FindWindow,導致取得 NULL 句柄,後續 SendMessage(WM_FIND...) 發送給無效目標。
// 錯誤:檔案剛載入,標題可能還是 "無標題 - 記事本"
HWND hNotepad = FindWindow("Notepad", null);
// 或硬編碼標題
HWND hNotepad = FindWindow(null, "無標題 - 記事本");
Thread.sleep(500~1000),等待視窗標題更新 (通常會顯示檔名)。EnumWindows 遍歷所有頂層視窗,比對類別名 "Notepad" 且可見、非最小化者。 IAccessible,不依賴標題字串。import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinDef.HWND;
public HWND findNotepad() {
final HWND[] result = {null};
User32.INSTANCE.EnumWindows((hWnd, lParam) -> {
char[] title = new char[512];
User32.INSTANCE.GetWindowText(hWnd, title, title.length);
String titleStr = Native.toString(title).trim();
char[] cls = new char[256];
User32.INSTANCE.GetClassName(hWnd, cls, cls.length);
String clsStr = Native.toString(cls).trim();
if ("Notepad".equals(clsStr) && !titleStr.isEmpty() && User32.INSTANCE.IsWindowVisible(hWnd)) {
result[0] = hWnd;
return false; // 停止枚舉
}
return true;
}, 0);
return result[0];
}
採用穩健的句柄獲取策略,即可解決「打開檔案後搜尋失效」的問題。