在KeyDown事件中检测单引号键
问题描述:
我希望TextBox只通过使用KeyDown事件接受某些特定字符。我已经有了它,除了一个字符,单引号。为了得到要写的字符,我使用(char)e.KeyValue
,它适用于除引号外的所有字符(它给出了Û)。我知道我可以使用e.KeyCode
,但它的价值是Keys.Oem4
,其中AFAIK可能在不同系统中有所不同。在KeyDown事件中检测单引号键
是否有任何方法一贯检测单引号按键?
代码片段:
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建议,this answer作品对我来说:
[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();
}
答
我一直在用这个很长一段时间。它处理单引号就好了。 e.KeyChar == 39'\''和e.Handled = true的行为与您所期望的完全相同。我使用KeyPress事件对其进行了测试,并在那里工作。
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar == (char)8) // backspace
return;
if (e.KeyChar == (char)3) // ctrl + c
return;
if (e.KeyChar == (char)22) // ctrl + v
return;
typedkey = true;
if (_allowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty
{
if (!_allowedCharacters.Contains(e.KeyChar)) // if the new character is not in allowed set,
{
e.Handled = true; // ignoring it
return;
}
}
if (_disallowedCharacters.Count > 0) // if the string of allowed characters is not empty, skip test if empty
{
if (_disallowedCharacters.Contains(e.KeyChar)) // if the new character is in disallowed set,
{
e.Handled = true; // ignoring it
return;
}
}
}
的'KeyPress'事件(我认为[是WM_CHAR](https://msdn.microsoft.com/en-us/library/windows/desktop/ms646276(V = vs.85)的.aspx ))使用'KeyPressEventArgs',它具有您正在查找的'KeyChar'属性。如果该事件能够满足您的需求,您可以使用它。 –
@EdPununkett说什么。 'KeyDown'和'KeyEventArgs'只给你虚拟键码,而不是真正的字符(它们经常在值中重合,所以演员的作品就是这样:巧合)。生成单引号的键的虚拟键代码因布局而异。问题不在于'KeyCode'; 'KeyValue'也不通用。 –
@EdPlunkett这样做,但我需要禁止按键,这只能在'KeyDown'事件中实现。 – Pipe