【发布时间】:2010-08-05 10:14:27
【问题描述】:
如何找到活动的子窗口(例如在模态对话框中进行焦点编辑)。我知道如何枚举子窗口,但我不知道如何检测子窗口是否处于活动状态(焦点)。
【问题讨论】:
-
rashim,请注意标签。 C# 没有 Windows。 Windows.Forms 库可以。
-
任何答案对您有帮助吗?请标记您选择的答案
如何找到活动的子窗口(例如在模态对话框中进行焦点编辑)。我知道如何枚举子窗口,但我不知道如何检测子窗口是否处于活动状态(焦点)。
【问题讨论】:
基本上它只是一个简单的 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);
}
}
}
【讨论】:
我在谷歌上尝试了 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);
【讨论】:
如果你正在寻找不同进程的活动子窗口,那么你可以将 IntPtr 匹配到子窗口到 IntPtr from
[DllImport("User32")]
public static extern IntPtr GetForegroundWindow();
如果这不是您要查找的内容,请您详细说明一下您的问题。
【讨论】:
如果你说的是 Mdi 子窗口,你可以使用 ActiveMdiChild,它是表单类的一个属性(在你的 mdiparent 上使用它)。
如果您谈论的是焦点控件,您可以使用 ActiveControl,它是每个容器控件(例如所有表单)的属性
【讨论】: