I’m trying to prevent the user from typing single quotes in the keypress event. Seems like a simple enough thing. All I have to work with is KeyChar. When I cast to a char and compare to Keys.Right (for right arrow) a single quote is a match for some odd reason. I am baffled by this. Any idea why a single quote would be a match for a right arrow? All the examples I see only do this same cast to compare against keys.
Func<char, bool> IsEditingKey = k =>
{
if (k == (char)Keys.Left || k == (char)Keys.Right || k == (char)Keys.Delete || k == (char)Keys.Back)
{
return true;
}
return false;
};
If I pass in a single quote (‘), when the test for k == (char)Keys.Right happens, it returns true. I now its a cast issue perhaps, but how else would I compare to make sure it is indeed the right arrow and not the single quote (‘)?
You are mixing up characters with virtual keys. Not the same thing. Keys.Right has the value 0x27.
'\''is also 0x27. One is an enumeration, the other is char.You’ll need to distinguish the two by using the proper event. The KeyDown event gives you virtual keys. The KeyPress event gives you the typing character, produced after the virtual key was converted by the user’s preferred keyboard layout. Since you are only interested in the character, not the virtual key, you must use KeyPress. Set e.Handled = true to suppress it.