【问题标题】:get descriptor of window [duplicate]获取窗口的描述符[重复]
【发布时间】:2012-02-14 18:53:20
【问题描述】:

可能重复:
Create an On-screen Keyboard

我正在尝试编写一个虚拟键盘。你能告诉我如何获得焦点窗口的描述符hWnd吗? (可以是 Word、Excel、Skype 等)

我使用的是findWindow(),但为此我必须知道窗口的名称。

IntPtr hWnd = FindWindow("Notepad", null);

        if (!hWnd.Equals(IntPtr.Zero))
        {
            MessageBox.Show("Tagil");
            IntPtr edithWnd = FindWindowEx(hWnd, IntPtr.Zero, "Edit", null);
            if (!edithWnd.Equals(IntPtr.Zero))
                SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, new StringBuilder("Hello World"));
        }

【问题讨论】:

  • 你想获取前景窗口的名称/句柄吗..?
  • 是的,但我认为不是前景,因为前景是我的应用。我想取名字或交给其他窗口
  • 最好使用 Windows Accessability API 来提供额外的键盘吗?

标签: c# c++ winapi


【解决方案1】:

不管怎样,这很可能是编写虚拟键盘的错误方法;您最好使用SendInput 注入击键,并让 Windows/USER32 处理将输入路由到当前焦点窗口本身 - 这样您甚至不需要首先知道当前焦点窗口.

一个问题是,虽然 Edit/Richedit 控件将使用 WM_SETTEXT,但许多其他现实世界的可编辑控件(如 Word、Excel 等)却不使用。此外,您不能使用 WM_SETTEXT 发送箭头键或其他非文本内容。

如果你仍然需要找到当前聚焦的 HWND,你可以使用GetGUIThreadInfo,为 idThread 传递 0,然后使用返回的 GUITHREADINFO 结构的 hwndFocus 成员。

【讨论】:

    【解决方案2】:

    HWND WINAPI GetForegroundWindow(void);

    检索前台窗口(用户当前正在使用的窗口)的句柄。系统会为创建前台窗口的线程分配比其他线程稍高的优先级。

    HWND WINAPI GetActiveWindow(void);

    检索附加到调用线程的消息队列的活动窗口的窗口句柄。

    其中一个可能会这样做。

    【讨论】:

    • GetActiveWindow 在这里没有用,因为窗口将驻留在不同的进程中。
    • GetForegroundWindow 和 GetActiveWindow 他们返回 Form1
    【解决方案3】:

    如果你想要一个更复杂的例子,你也可以看看这个

    在此处查看有关如何使用完整源代码执行此操作的示例:

    http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
    
    private string GetActiveWindowTitle()
    {
        const int nChars = 256;
        IntPtr handle = IntPtr.Zero;
        StringBuilder Buff = new StringBuilder(nChars);
        handle = GetForegroundWindow();
    
        if (GetWindowText(handle, Buff, nChars) > 0)
        {
            return Buff.ToString();
        }
        return null;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多