C# Detect Key Press, avoid non-typing keys
Is there any way to proceed into a method if the key that is being pressed does not result in any typing. i.e. the shift key, control key etc without having to specify all of them. Ideally, to detect combinations of keys, for example Control+V = Paste.
Code similar to below is what I am working with;
if( (e.KeyData == Keys.Left)
|| (e.KeyData == Keys.Right)
|| (e.KeyData == Keys.Home)
|| (e.KeyData == Keys.End)
|| (e.KeyData == Keys.Up)
|| (e.KeyData == Keys.Down)
|| (e.KeyData == Keys.Shift开发者_如何学运维Key)
|| (e.KeyData == Keys.ControlKey)
) return;
But don't want to add every single combination of keypresses.
Any ideas?
protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
{
if ( keyData == (Keys.Control | Keys.V) )
return true;
else
return base.ProcessCmdKey( ref msg, keyData );
}
That takes care of copy+paste. You can override OnKeyPress as well and use the Char.IsDigit and/or Char.IsLetter (or Char.IsLetterOrDigit) if needed. You get the idea, I don't think that a regular expression is warranted here as some others have suggested.
The Keys value contains bit combinations for all keys pressed... This means it can have more than one value at a given time. Try this:
if ( (keyData & Keys.Control) == Keys.Control && (keyData & Keys.V) == Keys.V)
{
// Ctrl+V was pressed!
}
So, that'll detect combinations of keys... BUT you are going to have to specify them :s
Check this out: http://www.go4expert.com/forums/showthread.php?t=713
This answers the inverse of your question--"proceed into a method if the key that is being pressed does not result in any typing"--but might get at what you're actually trying to accomplish, rather than the method.
I would suggest using the TextChanged event handler on the TextBox/RichTextBox control. This is only fired when the text actually changes (whether from the user typing, or from code).
private void richTextBox1_TextChanged(object sender, EventArgs e) {
// Handle the event.
}
If you want to know when it was the user that modified the content, you can use the Modified
property of the text box.
if (richTextBox1.Modified) {
// The user modified the contents of the text box.
}
This will likely be much more reliable than trying to handle the KeyDown, KeyUp, KeyPress, etc. events and figuring out from the keys that are pressed whether or not the text changed.
Perhaps it will serve your purpose to use a regular expression, with a "character class" that indicates non-printable characters.
For example, the unicode "general category" for control characters might work ('Cc').
精彩评论