How to find the active child window?

How to find the active child window (for example, Focus Edit in a modal dialog box). I know how to list child windows, but I don't know how to determine if a child window is active (focus).

+1
source share
4 answers

This is basically a simple Linq query:

var active = (from form in Application.OpenForms.OfType<Form>() where form.Focused select form).FirstOrDefault(); 

If active can be null or form. Just a short example with several forms:

 class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Form sample = new Form(); sample.Text = i.ToString(); sample.Show(); } while (true) { var active = (from form in Application.OpenForms.OfType<Form>() where form.Focused select form).FirstOrDefault(); if (active != null) Console.Write(active.Text); Application.DoEvents(); Thread.Sleep(100); } } } 
+1
source

If you are looking for the active child window of another process, you can map IntPtr to the child window with IntPtr from

  [DllImport("User32")] public static extern IntPtr GetForegroundWindow(); 

If this is not what you are looking for, could you please elaborate on your problem.

0
source

If you are talking about Mdi child windows, you can use ActiveMdiChild, which is a property of the form class (use it on your mdiparent).

If you're talking about focused controls, you can use ActiveControl, which is a property of every container control (for example, all of your forms).

0
source

I have an answer after you have tried more than two hours using Google. This is what I have:

 StringBuilder builder = new StringBuilder(500); int foregroundWindowHandle = GetForegroundWindow(); uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0); 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 int focused = GetFocus(); //Now detach since we got the focused handle AttachThreadInput(remoteThreadId, currentThreadId, false); 

Since we have a handle to the focus window, we can get its name / class, as well as other necessary information.

In this case, I just recognize the class name:

 StringBuilder winClassName = new StringBuilder(); int numChars = CustomViewAPI.Win32.GetClassName((IntPtr)focused, winClassName, winClassName.Capacity); 
0
source

Source: https://habr.com/ru/post/923604/


All Articles