More efficient way of screening KeyCodes on KeyDown Event - c#

I'm trying to fire an event perform some work when the user tries to enter only useful data into a form-field using the KeyDown event. But, I keep getting false alarms because the KeyDown event works for just any key!
I'm trying not to make the event fire for buttons such as "Alt, Control, Shift, Esc, the F-keys, etc." What's the best way of doing this?
What I have so far is this:
private void formControl_KeyModified(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Shift && e.KeyCode != Keys.CapsLock && e.KeyCode != Keys.Tab && e.KeyCode != Keys.Escape &&
e.KeyCode != Keys.Insert && e.KeyCode != Keys.Home && e.KeyCode != Keys.End && e.KeyCode != Keys.PageUp &&
e.KeyCode != Keys.PageDown && e.KeyCode != Keys.Up && e.KeyCode != Keys.Down && e.KeyCode != Keys.Left &&
e.KeyCode != Keys.Right && e.KeyCode != Keys.Control && e.KeyCode != Keys.Alt && e.KeyCode != Keys.NumLock &&
e.KeyCode != Keys.Insert && e.KeyCode != Keys.None && e.KeyCode != Keys.PrintScreen && e.KeyCode != Keys.Help &&
e.KeyCode != Keys.ControlKey && e.KeyCode != Keys.ShiftKey && e.KeyCode != Keys.Sleep && e.KeyCode != Keys.LWin &&
e.KeyCode != Keys.RWin && e.KeyCode != Keys.RMenu && e.KeyCode != Keys.LMenu && e.KeyCode != Keys.LShiftKey &&
e.KeyCode != Keys.RShiftKey && e.KeyCode != Keys.Pause && e.KeyCode != Keys.F1 && e.KeyCode != Keys.F2 &&
e.KeyCode != Keys.F3 && e.KeyCode != Keys.F4 && e.KeyCode != Keys.F5 && e.KeyCode != Keys.F6 && e.KeyCode != Keys.F7 &&
e.KeyCode != Keys.F8 && e.KeyCode != Keys.F9 && e.KeyCode != Keys.F10 && e.KeyCode != Keys.F11 && e.KeyCode != Keys.F12 &&
e.KeyCode != Keys.L)
{
// Do some work...
}
}
However, that doesn't quite seem like the best way to handle this to me. Again, I'm just trying to get keys for the characters that could be entered into a textbox (such as 213135udf!##%#!###%15nfaosdf~!#}{:?>, and so on)! Any help at all will be appreciated, thanks!
Sincerely,
Isaac D.
(Edited for clarity and quality)

You could throw all values into a HashSet<T> and check if the KeyCode is in the set.
var invalidKeys = new HashSet<Keys> { Keys.Shift, Keys.CapsLock, Keys.Tab, ... Keys.L };
if (!invalidKeys.Contains(e.KeyCode))
{
// Do some work...
}
Or alternatively, since you're checking for equality, you could just throw all that into a switch statement.
switch (e.KeyCode)
{
case Keys.Shift:
case Keys.CapsLock:
case Keys.Tab:
// ...
case Keys.L:
break;
default:
// Do some work...
break;
}

you can for example (there are many good attempts) check this page for help on the Char class where you can use methods like IsLetterOrDigit or other functions. Now I could not recognise if you are using Windows Forms? If so, use a simple cast like (char)e.KeyCode to get the char.
Example:
private void formControl_KeyModified(object sender, KeyEventArgs e)
{
char c = (char)e.KeyCode;
if (Char.IsLetterOrDigit(c)) {
// useful
}
// might add more checks
// else if (Char.IsPunctuation(c)) ...
}

You can handle the KeyPress event of the form. The mentioned event take a KeyPressEventArgs as its arguments parameter.
Use the Char.IsLetterOrDigit function to check the value of the KeyPressEventArgs.KeyChar property.
private void form_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (char.IsLetterOrDigit(e.KeyChar)) {}
else { e.Handled = false; }
}
EDIT:
You can also try to make a list of your accepted Char values, then check if the preseed character is included in it:
private void form_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
List<Char> charList = new List<Char>;
charList.AddRange(new Char[] { 'a', 'b' ... });
if (charList.Contains(e.KeyChar)) {}
else { e.Handled = false; }
}
You may need to consider combining both ways or even more to fulfill your requirements.

If you are concerned with the execution time of the if statement, create a SortedList of the Key values and check if the SortedList contains your key.
A possibly better solution is to use the Forms TextBox "TextChanged" event rather than using the KeyDown event.

Like #Daniel states in his comment, perhaps white-listing the valid keys is preferable than black-listing all those that are of no interest to you. So if, let's say, you are interested only in letter keys and numbers, you could do it just like it is described in the msdn Keys example
if(e.KeyCode > Keys.NumPad0 && e.KeyCode < Keys.NumPad9 ||
e.KeyCode > Keys.D0 && e.KeyCode < Keys.D9 ||
e.KeyCode > Keys.A && e.KeyCode < Keys.Z) {
//do useful stuff here
}

Related

WPF Key is digit or number

I have previewKeyDown method in my window, and I'd like to know that pressed key is only A-Z letter or 1-0 number (without anyF1..12, enter, ctrl, alt etc - just letter or number).
I've tried Char.IsLetter, but i need to give the char, so e.key.ToString()[0] doesn't work, because it is almost everytime a letter.
Something like this will do:
if ((e.Key >= Key.A && e.Key <= Key.Z) || (e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
Of course you will also have to check that no modifier keys like CTRL are pressed according to your requirements.
e.Key is giving you a member of the enum System.Windows.Input.Key
You should be able to do the following to determine whether it is a letter or a number:
var isNumber = e.Key >= Key.D0 && e.Key <= Key.D9;
var isLetter = e.Key >= Key.A && e.Key <= Key.Z;
In your specific case the answer provided by Jon and Jeffery is probably best, however if you need to test your string for some other letter/number logic then you can use the KeyConverter class to convert a System.Windows.Input.Key to a string
var strKey = new KeyConverter().ConvertToString(e.Key);
You'll still need to check to see if any modifier keys are being held down (Shift, Ctrl, and Alt), and it should also be noted that this only works for Letters and Numbers. Special characters (such as commas, quotes, etc) will get displayed the same as e.Key.ToString()
try this, it works.
private void txbNumber_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9) ; // it`s number
else if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ; // it`s number
else if (e.Key == Key.Escape || e.Key == Key.Tab || e.Key == Key.CapsLock || e.Key == Key.LeftShift || e.Key == Key.LeftCtrl ||
e.Key == Key.LWin || e.Key == Key.LeftAlt || e.Key == Key.RightAlt || e.Key == Key.RightCtrl || e.Key == Key.RightShift ||
e.Key == Key.Left || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Right || e.Key == Key.Return || e.Key == Key.Delete ||
e.Key == Key.System) ; // it`s a system key (add other key here if you want to allow)
else
e.Handled = true; // the key will sappressed
}
Add a reference to Microsoft.VisualBasic and use the VB IsNumeric function, combined with char.IsLetter().
bit of a cludge but it works :)
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
Regex R = new Regex("^([A-Z]|[0-9]){1}$");
var strKey = new KeyConverter().ConvertToString(e.Key);
if(strKey.Length > 1 )
{
strKey = strKey.Replace("NumPad", "").Replace("D", "");
}
if (strKey.Length == 1)
{
if (!R.IsMatch(strKey))
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
Can you put some code to show what you intend? Shouldn't this work for you
if(e.key.ToString().Length==1)
`Char.IsLetter(e.key.ToString()[0])`
else
//

Setting an attribute to only allow doubles in a textbox

I remember using some attribute on the getter/setter that would limit the input to a certain datatype, length etc. IE [Attribute something something].
Any ideas?
Thanks
Did you mean the ValidateInput attribute available in System.Web.Mvc?
Also, you could probably use a MaskedTextBox if you're doing WinForms.
One way to do it (if you want to keep using a standard text box) would be to make an event for the text changed event of the text box, and in that, read the text to make sure that it contains only numbers (and an optional period in the case of a double)
Winforms? Have you considered using masked Textbox control?
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Winforms? Why not use a NumericUpDown?
http://msdn.microsoft.com/en-us/library/57dy4d56.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.aspx
If you need scientific notation you can do :
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox tBox = (TextBox)sender;
if (!((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9)
|| (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)
|| (e.KeyCode == Keys.Decimal && !(tBox.Text.Contains('.'))
&& !(tBox.Text.Length == 0)
&& !((tBox.Text.Length == 1)
&& (tBox.Text.Contains('-') || tBox.Text.Contains('+'))))
|| (e.KeyCode == Keys.OemPeriod && !(tBox.Text.Contains('.'))
&& !(tBox.Text.Length == 0)
&& !((tBox.Text.Length == 1)
&& (tBox.Text.Contains('-') || tBox.Text.Contains('+'))))
|| (e.KeyCode == Keys.Subtract && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.OemMinus && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.Add && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| (e.KeyCode == Keys.Oemplus && ((tBox.Text.Length == 0) ||
tBox.Text.EndsWith("e") || tBox.Text.EndsWith("E")))
|| e.KeyCode == Keys.Delete
|| e.KeyCode == Keys.Back
|| e.KeyCode == Keys.Left
|| e.KeyCode == Keys.Right
|| (e.KeyCode == Keys.E) && !(tBox.Text.Contains('e')) &&
(tBox.Text.Contains('.') && !tBox.Text.EndsWith("."))))
{
e.SuppressKeyPress = true;
}
}
This will deny input of any pattern which is not consistent with a numeric value. Minus signs are only allowed at the beginning of the string (to indicate a negative number) and after an e or E to indicate a negative exponent. Plus signs follow the same rule as minus. Only one decimal point is allowed and it must follow at least one number. Only one e or E is allowed and it must follow a decimal point and at least one number after the decimal point.
You could also allow things like the Help, Tab, etc, keys if it would interfere with other aspects of your program function.
Note that this does not prevent incomplete numbers (ie: 1.37E- or -13. from being entered so you would probably want to check the string in any case. This at least denies any immediately invalid entries.
You might do something like (in the same handler, before the other logic):
if (e.KeyCode == Keys.Enter)
{
textBox1_Validating(sender, new CancelEventArgs());
return;
}
The above only gives the enter key the normal 'feel' for input (force validation). Leaving the textbox (going out of focus) will also trigger validation where you might do something like :
private void textBox1_Validating(object sender, CancelEventArgs e)
{
TextBox tBox = (TextBox)sender;
double tstDbl;
if (!double.TryParse(tBox.Text, out tstDbl))
{
//handle bad input
}
else
{
//double value OK
doSomething(tstDbl);
}
}

detect Ctrl + Enter

(using WPF)
i try to detect when Ctrl + Enter gets hit.
so i tried this code:
if (e.Key == Key.Return && (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl))
{
//Do Something
}
Obviously this is not correct, as it does not work.
Could anyone help me out, explaining what the right way should be ?
thanx
Obviously e.Key can't be equal to more than one different value in the same event.
You need to handle one of the events that uses KeyEventArgs, there you'll find properties such as Control and Modifiers that will help you detect combinations.
The KeyPress event, which uses KeyPressEventArgs, just doesn't have sufficient information.
Drat, you said WPF didn't you. It looks like you need e.KeyboardDevice.Modifiers.
I think you need a SpecialKey Handler.
I googled a bit a found a solution here.
Following code from the referred link may solve your problem:
void SpecialKeyHandler(object sender, KeyEventArgs e)
{
// Ctrl + N
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.N))
{
MessageBox.Show("New");
}
// Ctrl + O
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
{
MessageBox.Show("Open");
}
// Ctrl + S
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S))
{
MessageBox.Show("Save");
}
// Ctrl + Alt + I
if ((Keyboard.Modifiers == (ModifierKeys.Alt | ModifierKeys.Control)) && (e.Key == Key.I))
{
MessageBox.Show("Ctrl + Alt + I");
}
}
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Enter)
if (e.KeyChar == 10)
{
///Code
}
Or
if ((Char)e.KeyChar == '\n')
{
///Code
}

Silverlight textbox to accept only decimals

I have a Silverlight app with a textbox whose input I want to limit to decimal numbers only. Searching the web I came across the following possible solution (curiously in different places with different people claiming authorship of the same lines of code)
It appears to work well except that after at least 1 numeral has been entered it will then allow the letter 'd' in either upper or lower case to be entered, I can't figure out why that is and thus can't figure out how to prevent that from happening. Could anyone please provide a solution. Many thanks.
private void Unit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
}
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
You could try the following:
Replace the else with else if (e.Key != Key.D) or
set the Handled property like this:
e.Handled = !r.IsMatch(s) || string.IsNullOrEmpty(thisKeyStr);
// also possible:
e.Handled = !r.IsMatch(s) || e.Key == Key.D;
here is a easier code optimized. NO object creation; NO string comparision and NO regex validation
private static void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//platform code for Hyphen which is not same as Subtract symbol but in our case both give same meaning
const int KEYCODE_Hyphen_OnKeyboard = 189;
const int KEYCODE_Dot_OnKeyboard = 190;
const int KEYCODE_Dot_OnNumericKeyPad = 110;
e.Handled = !(
(!( //No modifier key must be pressed
(Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift
|| (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control
|| (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt
)
&& ( //only these keys are supported
(e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
|| e.Key == Key.Subtract || e.Key == Key.Add || e.Key == Key.Decimal
|| e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Delete
|| e.Key == Key.Tab || e.Key == Key.Enter || e.Key == Key.Escape || e.Key == Key.Back
|| (e.Key == Key.Unknown && (
e.PlatformKeyCode == KEYCODE_Hyphen_OnKeyboard
|| e.PlatformKeyCode == KEYCODE_Dot_OnKeyboard || e.PlatformKeyCode == KEYCODE_Dot_OnNumericKeyPad
)
)
)
)
);
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
bool isDigit = e.Key >= Key.D0 && e.Key < Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 ||
e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9 ||e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right;
if (isDigit) { }
else
e.Handled = true;
}

Keystroke combinations in c# winforms app

does anyone know how i can setup an event handler so that if the keystrokes Alt + Shift + Ctrl + a letter will do something?
override void OnKeyDown( object sender, KeyEventArgs e )
{
bool myKeysPressed = (e.KeyCode == Keys.A) &&
((e.Modifiers & Keys.Alt) == Keys.Alt) &&
((e.Modifiers & Keys.Shift) == Keys.Shift) &&
((e.Modifiers & Keys.Control) == Keys.Control);
}
Sames as Ed's, but shorter and more readable ;)
override void OnKeyDown( object sender, KeyEventArgs e )
{
bool myKeysPressed = (e.KeyCode == Keys.A) &&
e.Alt &&
e.Shift &&
e.Control;
}

Categories

Resources