Why PID equality breaks WebView2 focus detection—and how to verify focus safely
A desktop dictation tool has a deceptively dangerous job: it waits while speech recognition runs, then writes text into another application's focused control. If focus changes during that delay, the text may land in a chat, terminal, or password field the user never intended. In VocalCode I capture a focus token when recording starts and validate it again immediately before insertion. On Windows…
A desktop dictation tool must wait for speech recognition to finish before inserting text into another application's focused control. If focus changes during that delay, the text may end up in an unintended location. VocalCode captures a focus token during recording and validates it immediately before insertion. However, the original code incorrectly required the runtime ID of the focused element to match the PID of the foreground window.
This only works for Win32 controls but fails in Chromium, Electron, and WebView2 applications where the focused control may be in a separate renderer process. The mistake was treating process identity as proof of visual/window membership. The replacement algorithm captures the foreground window's HWND, obtains the focused element's runtime ID via UI Automation, and walks upward the raw-view tree until an element exposes its native window handle.
The root HWND is then compared to the captured foreground HWND. Both the foreground window and the focused UIA element are re-read after the ancestor walk to close any race conditions. At delivery, the token is validated again by matching the foreground HWND, renderer PID, and runtime ID to the original token. The core issue is that modern desktop UI processes may not match window boundaries.
To verify focus safety, check the control's membership in the user's foreground window instead of relying solely on process identity.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.