问题
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.
I have searched for keyboard hooks and winapi, but I couldn't find the proper method to use.
To simplify my problem, I need my application to be active if the user can press on the real keyboard and print text on the computer.
回答1:
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
}
}
回答2:
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.
回答3:
Here is an MSDN article on making a custom On Screen Keyboard: http://msdn.microsoft.com/en-us/magazine/hh708756.aspx
回答4:
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.
来源:https://stackoverflow.com/questions/12781059/how-to-know-if-the-keyboard-is-active-on-a-text-input