Hello,
I need to get the Handler to the child Window of a certain application that is running. I have the main window handler, but I need to know which specific child window is active, in order to use the SendMessage/PostMessage.
I finally managed to do this using the following code, using 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);
}
This works very well! However, if the application is not active, for example, if notepad is covering firefox, the GUIThreadInfo comes with every member null. Only if firefox is the top-most (active) application of windows, will the structure be filled.
I know this could be fixed by bringing firefox to the foreground but I needed to avoid doing this. Does anyone have any other idea to get the active child window of an application that is not the top-most window in Windows?
Thanks