问题
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.
I'm using windows forms.
回答1:
You can achieve what you want by first calling vkKeyScan to get the virtual-keycode for the char you're interested in.
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.
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:
1
!a
A
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.
The ToUnicode
handling was borrowed and adapted from this answer from user Timwi
来源:https://stackoverflow.com/questions/45017557/get-shift-representation-of-a-key-in-windows