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;
}
Related
I wish to validate this TextBox against negative values and characters (must be integer without decimal)
It works well for . but I am not able to understand why it accepts negative value and characters?
My code is :
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar == '.') && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back))
e.Handled = true;
}
You need to replace the first && operator with || and also move it to the end of your if statement then it should works as you want. Like this:
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back) || (e.KeyChar == '.'))
e.Handled = true;
}
I have 3 text-boxes in my C# Windows Form application for A, B and C respectively. Just like a simple scoring board.
What I want to do is when I press 'A' and then '1' the value in the text-box below should increment by 5 and when I press 'B' and then '1' the same should happen with the text-box below B and same as 'C'.
Just remember I don't want to use the combination keys. Below is the code for your reference:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = int.Parse(textBox1.Text);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (e.KeyCode == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = int.Parse(textBox2.Text);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
}
Considering you do NOT want to use combination keys, what you want to do is something similar to this (probably clean it up a little bit).
TextBox target;
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
target = textBox1;
}
if (e.KeyCode == Keys.B)
{
target = textBox2;
}
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
if(target != null)
{
int vA = int.Parse(target.Text);
vA += 5;
target.Text = (String)vA.ToString();
}
}
}
We can use a member variable to keep the value of last pressed key and use that variable inside KeyUp method to check the conditions.
public partial class Form1 : Form
{
Keys lastkeyPressed = Keys.Enter;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (lastkeyPressed == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = 0;
int.TryParse(textBox1.Text, out vA);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (lastkeyPressed == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = 0;
int.TryParse(textBox2.Text, out vB);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
if (lastkeyPressed == Keys.C)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vC = 0;
int.TryParse(textBox3.Text, out vC);
vC += 5;
textBox3.Text = (String)vC.ToString();
}
}
lastkeyPressed = e.KeyCode;
}
}
(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
}
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
}
On the text box, it should allow the user to enter only six decimal places. For example, 1.012345 or 1,012345.
If seven decimal places are tried, the entry should not be allowed.
Please refer to the below code.
private void textBox1_KeyDown_1(object sender, KeyEventArgs e)
{
bool numericKeys = (
( ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)) &&
e.Modifiers != Keys.Shift) ||
e.KeyCode == Keys.OemMinus ||
e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Oemcomma
);
bool navigationKeys = (
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End ||
e.KeyCode == Keys.Tab);
bool editKeys = (e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Back);
TextBox aTextbox = (TextBox)sender;
aTextbox.Text = "2,33333";
if (!string.IsNullOrEmpty(aTextbox.Text))
{
double maxIntensity;
string aTextValue = aTextbox.Text;
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
MessageBox.Show("the value is {0}", aText);
string[] args = aText.Split('.');
if (numericKeys)
{
bool handleText = true;
if (args.Length > 2)
{
handleText = false;
}
else
{
if (args.Length == 2 && args[1] != null && args[1].Length > 5)
{
handleText = false;
}
}
if (!handleText)
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
}
}
if (!(numericKeys || editKeys || navigationKeys))
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
To achieve the culture neutrality, the text value is converted to double first and then
the double value is converted to string.
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
}
Splitting the strings to separate the real part and mantissa part (both are stored are strings), then I check the length of the mantissa part. If the length of the string is more than 5, I'd like to suppress the key.
Is there aother approach to do this?
I've had luck with code similar to the following:
public class RegexMaskedTextBox : TextBox
{
private Regex _regex = new Regex(string.Empty);
public string RegexPattern
{
get { return _regex.ToString(); }
set { _regex = new Regex(value); }
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
string sNewText = this.Text;
string sTextToInsert = e.KeyChar.ToString();
if (this.SelectionLength > 0)
{
sNewText = this.Text.Remove(this.SelectionStart, this.SelectionLength);
}
sNewText = sNewText.Insert(this.SelectionStart, sTextToInsert);
if (sNewText.Length > this.MaxLength)
{
sNewText = sNewText.Substring(0, this.MaxLength);
}
e.Handled = !_regex.IsMatch(sNewText);
base.OnKeyPress(e);
}
}
I think I would solve this by using regular expressions. On the key down event you can check the regex.
Maybe you want to check this out: Regular expression for decimal number