0

我需要将处理程序获取到正在运行的某个应用程序的子窗口。我有主窗口处理程序,但我需要知道哪个特定的子窗口处于活动状态,以便使用 SendMessage/PostMessage。

我终于设法使用以下代码使用firefox做到了这一点:

    [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

    [DllImport("user32.dll", EntryPoint = "GetGUIThreadInfo")]
    internal static extern bool GetGUIThreadInfo(uint idThread, out GUITHREADINFO threadInfo);


    private void button1_Click(object sender, EventArgs e)
    {
        //start firefox
        firefox = new Process();
        firefox.StartInfo.FileName = @"C:\Program Files\Mozilla Firefox\firefox.exe";
        firefox.Start();
        Thread.Sleep(10000);

        // get thread of the main window handle of the process
        var threadId = GetWindowThreadProcessId(firefox.MainWindowHandle, IntPtr.Zero);

        // get gui info
        var info = new GUITHREADINFO();
        info.cbSize = (uint)Marshal.SizeOf(info);
        if (!GetGUIThreadInfo(threadId, out info))
            throw new Win32Exception();


        // send the letter W to the active window
        PostMessage(info.hwndActive, WM_KEYDOWN, (IntPtr)Keys.W, IntPtr.Zero);

    }

这很好用!但是,如果应用程序未处于活动状态,例如,如果记事本覆盖了 firefox,则 GUIThreadInfo 将带有每个成员 null。只有当 firefox 是 windows 的最顶层(活动)应用程序时,才会填充该结构。

我知道这可以通过将 firefox 置于前台来解决,但我需要避免这样做。有没有人有任何其他想法来获取不是 Windows 中最顶层窗口的应用程序的活动子窗口?

谢谢

4

2 回答 2

1

如果您拥有该进程的最顶层窗口句柄,您应该能够使用GetTopWindow接收位于 Z 顺序顶部的窗口。如果应用程序设置为活动/当前应用程序,这应该是活动的窗口。


编辑:

使用AttachThreadInput将您的线程附加到另一个进程线程怎么样?

完成此操作后,GetFocus() 和 PostMessage()/SendMessage() 应该可以工作。只要确保在完成后分离输入即可。

不幸的是,我能找到的唯一示例是在 Delphi 中,但很容易翻译。

于 2009-05-07T00:17:01.877 回答