我希望 TextBox 使用 KeyDown 事件仅接受某些特定字符。我已经让它工作了,除了一个字符,单引号。为了获得将要写入的字符,我使用(char)e.KeyValue
它适用于除引号之外的所有字符(它给出了 Û)。我知道我可以使用,e.KeyCode
但它的价值是Keys.Oem4
,AFAIK 可能因系统而异。
有没有办法始终如一地检测单引号按键?
代码片段:
char c = (char)e.KeyValue;
char[] moves = { 'r', 'u', ..., '\'' };
if (!(moves.Contains(c) || e.KeyCode == Keys.Back || e.KeyCode == Keys.Space))
{
e.SuppressKeyPress = true;
}
正如@EdPlunkett 所建议的,这个答案对我有用:
[DllImport("user32.dll")]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
static extern IntPtr GetKeyboardLayout(uint idThread);
[DllImport("user32.dll")]
static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl);
public static string KeyCodeToUnicode(System.Windows.Forms.Keys key)
{
byte[] keyboardState = new byte[255];
bool keyboardStateStatus = GetKeyboardState(keyboardState);
if (!keyboardStateStatus)
{
return "";
}
uint virtualKeyCode = (uint)key;
uint scanCode = MapVirtualKey(virtualKeyCode, 0);
IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);
StringBuilder result = new StringBuilder();
ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, (uint)0, inputLocaleIdentifier);
return result.ToString();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句