How to enable control key functionality in windows form application? - c#

I am using the following textbox keypress() event to capture the keystrokes entered by user to restrict user to enter alphabet and numeric values.
private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) ||
e.KeyChar == (char)Keys.Space ||
e.KeyChar == (char)Keys.Back ||
e.KeyChar==(char)Keys.ControlKey );
}
Now the problem is by using the above mentioned code I am not able to use shortcut keys like Ctrl+C or Ctrl+v even if keys.ControlKey is handled in the the keypress event.
What i am doing wrong here?
Thanks in advance.

The Keypress event is not raised if the Control key is pressed without any other key. Is used as a key modifier only. In this case, e.KeyChar returns a modified value that char.IsLetter() considers false, the ! operator transforms it in true and assigns it to e.Handled, thus the keypress event is canceled.
to capture the keystrokes entered by user to restrict user to enter
alphabet and numeric values.
If, as you said, numbers are part of the required input, char.IsLetterOrDigit() should be used instead of char.IsLetter().
And punctuation? Is part of the input too?
These symbols are considered punctuation by char.IsPunctuation(): \"%&/()?*#.,:;_-'
Two methods to have the same result.
In both, char.IsControl(e.KeyChar) is used to check if Control is part of the Keycode and if it is, strip it by XOR(ing) it.
1) Filter using a simple regex. This one gives you more control on what to filter.
Regex _KeyFilter = new Regex(#"^[a-zA-Z0-9.,]");
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
e.Handled = !_KeyFilter.IsMatch((char.IsControl(e.KeyChar)
? (char)(e.KeyChar ^ 64)
: e.KeyChar).ToString());
}
}
2) Filtert using char.IsLetterOrDigit() and char.IsPunctuation()
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
char _keypress = char.IsControl(e.KeyChar) ? (char)(e.KeyChar ^ 64) : e.KeyChar;
e.Handled = !char.IsLetterOrDigit(_keypress) && !char.IsPunctuation(_keypress);
}
}

Related

How to make keypress oemMinus and oemComma ( + digits) acceptable

I have a textbox in my application which I only want the user to be able to choose the "minus", "comma", "digits" and "back" from the keyboard. Can only make the user use digits and the back key, the rest doesn't work.
private void BoxMaxY_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back ||
!(e.KeyChar == (char)Keys.OemMinus || !(e.KeyChar == (char)Keys.Oemcomma))))
{
e.Handled = true;
}
}
Because your code says: handle if it's not minus or not comma, remove the "!" from those checks.

C# When using a KeyPress event on a text box, why cant i enter a minus sign?

Im using VS2010, and I have a text box... I assign a KeyPress on the box, abd set the method like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
I noticed that i am no longer able to enter any special keys such as the minus (-) and plus (+) sign into the textbox. Can someone please explain to me why i am no longer able to do this, and what i can do to fix this?
Ultimately I'm trying to only allow numeric keys to be entered, and i also want to allow the (-) minus sign, but if i cant get the minus sign in there, then i guess i wont be able to limit the text of the box
This should finish the job for you.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
e.Handled = true;
}
Here is how it works. If the character typed is one that you want, simply return from the function and let the normal handler take care of it. All other characters are marked as handled and so processing on them stops. Since nothing is done with them they are essentially thrown away. You could put everything in one if statement but I left it this way for clarity
I changed your code a little and added logic that only accepts 1, 2 or +, which was one of your problem characters. Hope this helps you!
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+') textBox1.AppendText(e.KeyChar.ToString());
}
Actually, you should do like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+')
e.Handled = false;
else
e.Handled = true;
}
Of course, you'll want to replace the individual tests by a method that will return whether or not the key is allowed.
Cheers
As it is now, your code won't allow anything to be entered. The e.Handled statement cancels the key stroke. The code below will allow any numeric character, and the minus sign. If you only want the minus sign in the first position in the textbox you will have to test the TextLength property before allowing the character.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e
{
int i = 0;
if (!int.TryParse(e.KeyChar.ToString(), out i))
{
if (e.KeyChar.CompareTo('-')!=0)
{
e.Handled = true;
}
}
}

How can I determine if the Backspace has been pressed in the KeyPress event?

This:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx
...indicates that I should have access to e.KeyCode in the KeyPress event, but I don't seem to. I'm trying to allow only 1,2,3, and backspace:
private void textBoxQH1_KeyPress(object sender, KeyPressEventArgs e) {
if ((e.KeyChar != '1') &&
(e.KeyChar != '2') &&
(e.KeyChar != '3') &&
(e.KeyChar != (Keys.Back))) {
e.Handled = true;
}
}
...but "e." does not show a "KeyCode" value like the example shows, and trying KeyChar with Keys.Back scolds me with, "Operator '!=' cannot be applied to operands of type 'char' and 'System.Windows.Forms.Keys'"
So how can I accomplish this?
try comparing e.KeyChar != (char)Keys.Back, you should cast it to char since Keys is an enumeration
see this: KeyPressEventArgs.KeyChar
I'm pretty sure I've only ever solved this by using the KeyDown event instead; it has different event arguments.
Try to put a condition like this:
Code :
if (e.KeyCode == (Keys.Back))
{
if(textBox1.Text.Length >=3)
{
if (textBox1.Text.Contains("-"))
{
textBox1.Text.Replace("-", "");
}
}
}

C# Numeric Only TextBox Control [duplicate]

This question already has answers here:
numeric-only textbox as a control in Visual Studio toolbox
(4 answers)
Closed 9 years ago.
I am using C#.NET 3.5, and I have a problem in my project. In C# Windows Application, I want to make a textbox to accept only numbers. If user try to enter characters message should be appear like "please enter numbers only", and in another textbox it has to accept valid email id message should appear when it is invalid. It has to show invalid user id.
I suggest, you use the MaskedTextBox: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
From C#3.5 I assume you're using WPF.
Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.
For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.
Look up Binding on MSDN.
use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
You might want to try int.TryParse(string, out int) in the KeyPress(object, KeyPressEventArgs) event to check for numeric values. For the other problem you could use regular expressions instead.
I used the TryParse that #fjdumont mentioned but in the validating event instead.
private void Number_Validating(object sender, CancelEventArgs e) {
int val;
TextBox tb = sender as TextBox;
if (!int.TryParse(tb.Text, out val)) {
MessageBox.Show(tb.Tag + " must be numeric.");
tb.Undo();
e.Cancel = true;
}
}
I attached this to two different text boxes with in my form initializing code.
public Form1() {
InitializeComponent();
textBox1.Validating+=new CancelEventHandler(Number_Validating);
textBox2.Validating+=new CancelEventHandler(Number_Validating);
}
I also added the tb.Undo() to back out invalid changes.
this way is right with me:
private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
You can check the Ascii value by e.keychar on KeyPress event of TextBox.
By checking the AscII value you can check for number or character.
Similarly you can write logic to check the Email ID.
I think it will help you
<script type="text/javascript">
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 32 && (charCode < 48 || charCode > 57) && (charCode != 45) && (charCode != 43) && (charCode != 40) && (charCode != 41))
return false;
return true;
}
try
{
int temp=Convert.ToInt32(TextBox1.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}

Win Forms text box masks

How can I put mask on win form text box so that it allows only numbers?
And how it works for another masks data, phone zip etc.
I am using Visual Studio 2008 C#
Thanks.
You can use the MaskedTextBox control
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Do you want to prevent input that isn't allowed or validate the input before it is possible to proceed?
The former could confuse users when they press keys but nothing happens. It is usually better to show their keypresses but display a warning that the input is currently invalid. It's probably also quite complicated to set up for masking an email-address regular expression for example.
Look at ErrorProvider to allow the user to type what they want but show warnings as they type.
For your first suggestion of a text box that only allows numbers, you might also want to consider a NumericUpDown.
Control the user's key press event to mask the input by not allowing any unwanted characters.
To allow only numbers with decimals:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
To allow only phone numbers values:
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
if (e.KeyChar == 8) return;
e.Handled = true;
}
As said above, use a MaskedTextBox.
It's also worth using an ErrorProvider.
Use Mask Text box and assign MasktextboxId.Mask.
If u want to use textbox then you have to write Regular Expression for it

Categories

Resources