【问题标题】:How can I find the active child window?如何找到活动的子窗口?
【发布时间】:2010-08-05 10:14:27
【问题描述】:

如何找到活动的子窗口(例如在模态对话框中进行焦点编辑)。我知道如何枚举子窗口,但我不知道如何检测子窗口是否处于活动状态(焦点)。

【问题讨论】:

  • rashim,请注意标签。 C# 没有 Windows。 Windows.Forms 库可以。
  • 任何答案对您有帮助吗?请标记您选择的答案

标签: .net winforms


【解决方案1】:

基本上它只是一个简单的 Linq 查询:

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

其中 active 可以是 null 或表单。只是一个带有几种形式的简短示例:

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

  }
}

【讨论】:

  • 这个有我的投票。 IMO,这个查询在流畅的语法中看起来更好一些: Application.OpenForms.OfType
    () .FirstOrDefault(f=>f.Focused)
【解决方案2】:

我在谷歌上尝试了 2 个多小时后得到了答案。这就是我所拥有的:

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

由于我们有焦点窗口的句柄,我们可以得到它的名称/类以及其他必要的信息

在这种情况下,我只是找出类名:

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

【讨论】:

    【解决方案3】:

    如果你正在寻找不同进程的活动子窗口,那么你可以将 IntPtr 匹配到子窗口到 IntPtr from

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

    如果这不是您要查找的内容,请您详细说明一下您的问题。

    【讨论】:

    • 实际上我正在使用模态对话框。在这种情况下,它首先关注地址栏。如果我们按 Tab 键,它会聚焦在编辑框上。所以我想知道我现在应该如何检测哪个控制窗口已经聚焦?
    【解决方案4】:

    如果你说的是 Mdi 子窗口,你可以使用 ActiveMdiChild,它是表单类的一个属性(在你的 mdiparent 上使用它)。

    如果您谈论的是焦点控件,您可以使用 ActiveControl,它是每个容器控件(例如所有表单)的属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-29
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 2012-04-16
      相关资源
      最近更新 更多