我想将 pressKey 事件发送到某个应用程序,该应用程序不是 Windows 中的事件应用程序,因此我必须使用 sendMessage/postMessage api 调用。
但是,我需要知道在应用程序中处于事件状态的确切子窗口并将 pressKey 消息发送给它...
我正在使用 GetTopWindow 和 GetWindow(GW_CHILD) api 调用来获取主窗口的顶部子窗口,然后用获得的子窗口再次执行此操作以获得顶部孙窗口,并继续这样做,直到我找到一个子窗口没有更多的子窗口。这对某些应用程序非常有用,但在某些情况下却行不通。有时父窗口是事件窗口,而不是其子窗口之一,因此获取父窗口的顶部子窗口将不起作用,因为我会向错误的窗口发送消息。
我发现这样做(获取实际事件窗口的处理程序)的唯一方法是使用 GuiThreadInfo api 调用,但它仅在目标应用程序是 Windows 中的事件应用程序时才有效。正如我在开头提到的那样,处理程序并非如此。
我可以使用 setForegroundWindow api 调用将应用程序置于顶部,但我不想这样做。我还尝试了 AttachThreadInput 和 GetFocus api 调用,但同样,它们仅在目标应用程序是 Windows 中的事件应用程序时才有效。
有什么想法吗?谢谢
最佳答案
根据您尝试过的事情,我假设您知道如何获取主窗口的句柄,但如果您不留下评论,我会为此发布一个片段。
我结合了一些我在网上找到的东西来解决这个问题,但主要的是这个 one .我没有一个很棒的应用程序来测试它,但它可以在一个简单的案例中使用。一个异常(exception)是,我认为如果你在你的应用程序中使用工具窗口,它不会发现它是编码的,因为我认为 GetLastActivePopup 方法不包括它们(对此不确定,并且没有测试这种情况)。
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr GetLastActivePopup(IntPtr hWnd);
[DllImport("user32.dll", ExactSpelling = true)]
static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags);
const uint GA_PARENT = 1;
const uint GA_ROOT = 2;
const uint GA_ROOTOWNER = 3;
public static IntPtr GetAppActiveWindow(IntPtr hwnd)
{
IntPtr activeAppWindow = IntPtr.Zero;
if (hwnd != IntPtr.Zero)
{
//Get the root owner window (make sure we are at the app window
//if you already have a handle to the main window shouldn't have
//to do this but I put it in just in case
hwnd = GetAncestor(hwnd, GA_ROOTOWNER);
while ((activeAppWindow =
GetLastActivePopup(hwnd)) != activeAppWindow)
{
if (IsWindowVisible(activeAppWindow))
break;
hwnd = activeAppWindow;
}
}
return activeAppWindow;
}
关于c# - 如何获取应用程序的事件 ChildWindow?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/842539/