如何获得前景窗口的键盘状态? 我搜索过但没有帮助
[DllImport("user32.dll")]
public static extern bool GetKeyboardState(byte[] lpKeyState);
获取当前应用程序键盘状态而不是外部窗口(活动窗口)
更新 我做了像slashy说的但是仍然什么都没有,但是什么时候我知道什么都没有,所以任何人都可以告诉我这个代码有什么不对
public static char GetCharFromKey(Key key)
{
char ch = ' ';
int virtualKey = KeyInterop.VirtualKeyFromKey(key);
uint x = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
StringBuilder stringBuilder = new StringBuilder(2);
int result = ToUnicode((uint)virtualKey, scanCode, Encoding.ASCII.GetBytes(GetKeyboardLayout(x).ToString()), stringBuilder, stringBuilder.Capacity, 0);
switch (result)
{
case -1:
break;
case 0:
break;
case 1:
{
ch = stringBuilder[0];
break;
}
default:
{
ch = stringBuilder[0];
break;
}
}
return ch;
}
仍然让我的应用程序键盘状态不是前景
答案 0 :(得分:-2)
首先应该获取窗口处理程序,然后找到键盘状态:
Dll导入
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
[DllImport("user32.dll")]
static extern IntPtr GetKeyboardLayout(uint idThread);
代码:
uint x = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
keyboard = GetKeyboardLayout(x).ToString();//holds the state