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

前端 未结 4 1022
予麋鹿
予麋鹿 2021-01-23 07:57

I have an application that acts like an on screen keyboard, I need it to know if there is a keyboard cursor (caret) active any where, so the keyboard will set to active.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-23 08:12

    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.

提交回复
热议问题