How to know if the keyboard is active on a text input

戏子无情 提交于 2019-12-02 04:01:47

It is easy by searching for the caret position, since it should be larger than 0

    GUITHREADINFO lpgui = new GUITHREADINFO();
    IntPtr fore = GetForegroundWindow();
    uint tpid = GetWindowThreadProcessId(fore, IntPtr.Zero);
    lpgui.cbSize = Marshal.SizeOf(lpgui.GetType());
    bool flag = GetGUIThreadInfo(tpid, out lpgui);
    WINDOWINFO pwi = new WINDOWINFO();
    pwi.cbSize = (uint)Marshal.SizeOf(pwi.GetType());
    GetWindowInfo((IntPtr)lpgui.hwndCaret, ref pwi);

    if (flag)
    {
        if (!(lpgui.rcCaret.Location.X == 0 && lpgui.rcCaret.Location.Y == 0))
        {


            //TODO

        }
    }

Bit of a workaround, but if you can subscribe to a OnFocusChange event in your environment then you can check the type of control that newly received focus. Depending on if it is a 'keyboardable' type (or is derived from a 'keyboardable' type) you can display or hide your onscreen keyboard.

Here is an MSDN article on making a custom On Screen Keyboard: http://msdn.microsoft.com/en-us/magazine/hh708756.aspx

Mike Perrenoud

Define a DLLImport so that you can get the currently focused window handle:

[DllImport("user32.dll")]
static extern IntPtr GetFocus();

Now, you can run this to get that window handle if there is something focused for the keyboard:

public static bool ControlIsFocused() 
{
    // To get hold of the focused control: 
    IntPtr focusedHandle = GetFocus(); 
    return focusedHandle != IntPtr.Zero;
}

So, unless it's a control that allows keyboard focus this method should return IntPtr.Zero.

Here is a link to the Windows API.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!