アプリケーション固有のウィンドウ用の特定の wHnd (ウィンドウ ハンドル) が必要です: Google Chrome/Firefox Web ページのテキスト (フォームの TextBox ではありません)。リスト ボックスとシステム ツリーも、通常の呼び出しを使用して戻りません (以下のコード スニペット)。非常に有益なもう 1 つのアプリケーション固有のウィンドウは、Visual Studios コード ウィンドウです (コード ウィンドウだけでなく、常により多くの情報が役立ちます!!)。助けてくれてありがとう。
using System.Runtime.InteropServices;
public static class WindowUtils {
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern IntPtr GetWindowThreadProcessId(
IntPtr hWnd,
IntPtr ProcessId);
[DllImport("user32.dll")]
static extern IntPtr AttachThreadInput(
IntPtr idAttach,
IntPtr idAttachTo,
bool fAttach);
[DllImport("user32.dll")]
static extern IntPtr GetFocus();
public IntPtr GetFocusedControl() {
IntPtr activeWindowHandle = GetForegroundWindow();
IntPtr activeWindowThread =
GetWindowThreadProcessId(activeWindowHandle, IntPtr.Zero);
IntPtr thisWindowThread =
GetWindowThreadProcessId(this.Handle, IntPtr.Zero);
AttachThreadInput(activeWindowThread, thisWindowThread, true);
IntPtr focusedControlHandle = GetFocus();
AttachThreadInput(activeWindowThread, thisWindowThread, false);
return focusedControlHandle;
}
}