2012-02-14 157 views
1

可能重复:
Create an On-screen KeyboardGET描述符

我试图写一个虚拟键盘。你能告诉我如何获得关注窗口的描述符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")); 
     } 
+0

你想获得前景窗口的名称/句柄..? – MethodMan 2012-02-14 19:00:46

+0

是的,但我认为不是前景,因为前景是我的Apllictation。我想获取名称或交付其他窗口 – Abbath 2012-02-15 08:35:17

+0

最好使用Windows [Accessability API](http://msdn.microsoft.com/en-us/library/windows/desktop/gg712214.aspx)提供额外的键盘? – Deanna 2012-08-09 08:32:09

回答

0

HWND WINAPI GetForegroundWindow(void);

检索的句柄前台窗口(与该用户当前工作的窗口)。系统为创建前景窗口的线程分配比其他线程稍高的优先级。

HWND WINAPI GetActiveWindow(void);

检索窗口句柄连接到调用线程的消息队列中的活动窗口。

其中一个可能会这样做。

+0

'GetActiveWindow'在这里没有用,因为窗口将驻留在不同的进程中。 – 2012-02-14 21:37:01

+0

GetForegroundWindow和GetActiveWindow它们返回Form1 – Abbath 2012-02-15 06:56:44

0

,如果你想在这里更复杂的例子,你可以看看这个问题,以及

示例见你如何能做到这一点了完整的源代码在这里:

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; 
} 
+0

http://www.csharphelp.com/archives2/archive301.html在这个链接空白页 – Abbath 2012-02-15 06:57:31

+0

更新到更新后的链接 – BrianH 2012-08-08 16:07:39

2

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

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

如果您仍然确实需要查找当前关注的HWND,则可以使用GetGUIThreadInfo,将idThread传递为0,然后使用返回的GUITHREADINFO结构的hwndFocus成员。