My task was to to find the foreground window (accomplished using GetForegroundWindow API) and then I had to pre-populate a list which contained all the child windows of the foreground window (accomplished using EnumChildWindows API).Now I need to detect that the mouse cursor is on which child window i.e. I need to find out which child window (may be a button or a textbox in the foreground window) is Active. Is there some API using which I can get handles of the ChildWindows which have been clicked ? Even if I get just the name of the ChildWindow(of the active foreground window) on which the focus is, it is enough for me. Thanks in Advance.
Asked
Active
Viewed 1,020 times
3
-
Why are you messing with another application's windows? If this is for test automation, you can use the System.Windows.Automation namespace. – Raymond Chen Apr 10 '12 at 09:21
-
This is no test Automation....It takes a lot of time to explain what my app intends to do, but I'll brief you up quickly, I have to pre populate the list of childwindows which are there in the active application, track the movements(clicks) of the user and guide him as to what he has to do next, by referring the look up which has been made using EnumChildWindows, so for that I need to know exactly which child window is having the focus. Can you please give me some pointers as to how it can be done using System.Windows.Automation.... Thanks in advance! – Ajit Apr 10 '12 at 11:48
-
Oh, this is for computer-based training. System.Windows.Automation may still be useful. You can read the documentation to get up to speed; I'm not going to try to teach you in a comment. – Raymond Chen Apr 10 '12 at 13:44
-
Ok Thanks, I'm into it right away – Ajit Apr 10 '12 at 17:18
1 Answers
4
InPtr hwnd = GetForegroundWindow();
public static void GetAppActiveWindow(IntPtr hwnd)
{
uint remoteThreadId = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
uint currentThreadId = GetCurrentThreadId();
//AttachTrheadInput is needed so we can get the handle of a focused window in another app
AttachThreadInput(remoteThreadId, currentThreadId, true);
//Get the handle of a focused window
IntPtr focussed = GetFocus();
StringBuilder activechild = new StringBuilder(256);
GetWindowText(focussed, activechild, 256);
string textchld = activechild.ToString();
if (textchld.Length > 0)
{
Console.WriteLine("The active Child window is " + textchld + " .");
}
//Now detach since we got the focused handle
AttachThreadInput(remoteThreadId, currentThreadId, false);
}
This is what which finally solved the problem :)

Ajit
- 964
- 10
- 17
-
Great piece of code. It helped sending messages by either post or send message and get them work in every situation. I just converted it to bool and it returns whether the foreground window is child or not. Thank you. – W.M. Aug 17 '21 at 18:55