开发者

How can I find the active child window?

开发者 https://www.devze.com 2023-01-10 20:09 出处:网络
How can I find the active child window (like focus Edit in modal dialog). 开发者_Python百科I know how to enumerate child windows, but I don\'t know how to detect if a child window is active (focus).I

How can I find the active child window (like focus Edit in modal dialog). 开发者_Python百科I know how to enumerate child windows, but I don't know how to detect if a child window is active (focus).


I have got an answer after trying more than 2 hour with google. This is what I've got :

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);

As we have the handle of the focus window we could get it name/Class and also other necessary information

In this case I just find out the class name:

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


Basically it's just a simple Linq query:

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

Where active can be null or a form. Just a short example with few 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);
    }

  }
}


If you are looking for the active child window of a different process, then you can match the IntPtr to the child window to the IntPtr from

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

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


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

If you are speaking about focused controls, you can get using ActiveControl, which is a property of every container control (e.g. all your forms)

0

精彩评论

暂无评论...
验证码 换一张
取 消