问题描述
是否有内置的方法来获取与 Shift 键相结合的键的等效项,例如:
Is there a built in way to obtain the equivalent of a key combined with the Shift key e.g:
a + Shift -> A
1 + Shift ->!
我目前将所有键映射到字典中的方式与上面说明的大致相同.
I currently have all the keys mapped in a dictionary in pretty much the same way as illustrated above.
我正在使用Windows窗体.
I'm using windows forms.
推荐答案
您可以通过首先调用 vkKeyScan 来获取您感兴趣的字符的虚拟键代码.
You can achieve what you want by first calling vkKeyScan to get the virtual-keycode for the char you're interested in.
有了该呼叫的结果,您可以提供 ToUnicode
来转换按下Shift键时的字符.
With the outcome of that call you can feed ToUnicode
to translate what the characters would be when the Shift key is pressed.
上述两种方法都是键盘和鼠标输入类别.
Both above mentioned methods are native WinAPI calls in the KeyBoard and Mouse input category.
结合以上调用并在C#中实现,您将获得以下实现(已在LinqPad中进行了测试):
Combining above calls and implementing in C# you'll get the following implementation (tested in LinqPad):
void Main()
{
GetCharWithShiftPressed('1').Dump("1");
GetCharWithShiftPressed('a').Dump("a");
}
// Inspired on https://stackoverflow.com/a/6949520
// TimWi: https://stackoverflow.com/users/33225/timwi
public static string GetCharWithShiftPressed(char ch)
{
// get the keyscancode
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms646329(v=vs.85).aspx
var key = Native.VkKeyScan(ch);
// Use toUnicode to get the actual string shift is pressed
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms646320(v=vs.85).aspx
var buf = new StringBuilder(256);
var keyboardState = new byte[256];
keyboardState[(int) Keys.ShiftKey] = 0xff;
var result = Native.ToUnicode(key, 0, keyboardState, buf, 256, 0);
if (result == 0) return "No key";
if (result == -1) return "Dead key";
return buf.ToString();
}
// Define other methods and classes here
static class Native
{
[DllImport("user32.dll")]
public static extern uint VkKeyScan(char ch);
[DllImport("user32.dll")]
public static extern int ToUnicode(uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
StringBuilder receivingBuffer,
int bufferSize,
uint flags);
}
运行以上代码,您将获得以下输出:
Running above code you'll get the following output:
a
a
A
此实现使用当前的活动键盘布局.如果您想指定其他键盘布局,请使用 ToUnicodeEx
,它将键盘布局的句柄作为最后一个参数.
This implementation uses the current active keyboard layout. If you instead want to specify alternative keyboard layouts, use the ToUnicodeEx
that takes an handle to a keyboardlayout as its last parameter.
ToUnicode
处理是从用户此答案中借用并改编的. stackoverflow.com/users/33225/timwi">Timwi
The ToUnicode
handling was borrowed and adapted from this answer from user Timwi
这篇关于在Windows中获取键的"Shift"表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!