Search code examples
c#winapichildwindow

Detect which childwindow of the foreground window has been clicked?


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.


Solution

  •       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 :)