実行中の特定のアプリケーションの子ウィンドウに Handler を取得する必要があります。メイン ウィンドウ ハンドラはありますが、SendMessage/PostMessage を使用するには、アクティブな特定の子ウィンドウを知る必要があります。
私は最終的に、Firefoxを使用して、次のコードを使用してこれを行うことができました:
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll", EntryPoint = "GetGUIThreadInfo")]
internal static extern bool GetGUIThreadInfo(uint idThread, out GUITHREADINFO threadInfo);
private void button1_Click(object sender, EventArgs e)
{
//start firefox
firefox = new Process();
firefox.StartInfo.FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe";
firefox.Start();
Thread.Sleep(10000);
// get thread of the main window handle of the process
var threadId = GetWindowThreadProcessId(firefox.MainWindowHandle, IntPtr.Zero);
// get gui info
var info = new GUITHREADINFO();
info.cbSize = (uint)Marshal.SizeOf(info);
if (!GetGUIThreadInfo(threadId, out info))
throw new Win32Exception();
// send the letter W to the active window
PostMessage(info.hwndActive, WM_KEYDOWN, (IntPtr)Keys.W, IntPtr.Zero);
}
これはとてもうまくいきます!ただし、アプリケーションがアクティブでない場合 (たとえば、メモ帳が Firefox をカバーしている場合)、GUIThreadInfo にはすべてのメンバーが null になります。Firefox が Windows の最上位 (アクティブ) アプリケーションである場合にのみ、構造が満たされます。
Firefox をフォアグラウンドにすることでこれを修正できることはわかっていますが、これを避ける必要がありました。Windows の一番上のウィンドウではないアプリケーションのアクティブな子ウィンドウを取得する他のアイデアはありますか?
ありがとう