I'd like to process an alphabetic character and underscores. How do I tell what char is typed if a SHIFT is also pressed. Currently, shifted chars are handled by the ELSE clause.
private void txtSearch_KeyUp(object sender, KeyEventArgs e)
{
if (((int)e.KeyData >= 65 && (int)e.KeyData <= 122) ||
(e.KeyData.ToString() == "_"))
{
System.Diagnostics.Debug.WriteLine(e.KeyData);
//char thisChar = char excluding SHIFT, Control
System.Diagnostics.Debug.WriteLine("Process " + thisChar);
}
else
{
System.Diagnostics.Debug.WriteLine("Throw away a " + e.KeyData);
}
}
if (e.Shift && (((int)e.KeyData >= 65 && (int)e.KeyData <= 122) || (e.KeyData.ToString() == "_")))
{
//Code here
}
G'day,
I took a slight different approach:
private void txtSearch_KeyUp(object Sender, KeyEventArgs E)
{
int iKeyData = (int)(E.KeyData);
if (((E.KeyData.HasFlag(Keys.OemMinus) == true) && (E.Shift == true)) || ((iKeyData >= 65) && (iKeyData <= 122)))
{
System.Diagnostics.Debug.WriteLine(E.KeyData);
}
else
{
System.Diagnostics.Debug.WriteLine("Throw away a " + E.KeyData);
}
}
I'm not sure how this will work with different keyboard layouts though - might want to look into that too.
Cheers!
Related
I'm having trouble with this code. I want it to make the first letter of the Textbox upper case, but if the textbox is empty the program crashes. I know the problem is to do with the length of the substring, so if anyone can help me fix this it would be great!
NB: The name of the textbox is richTextBoxGuess and this code runs every time the text in the textbox changes.
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ) // Checks if first letter is lower case
{
richTextBoxGuess.Text = richTextBoxGuess.Text.Replace(richTextBoxGuess.Text.Substring(0, 1), richTextBoxGuess.Text.ToUpper()); // Changes first letter to uppercase
richTextBoxGuess.SelectionStart = 2; // Puts cursor after first letter
}
This will not destroy the previous formatting of the content:
private void richTextBoxGuess _TextChanged(object sender, EventArgs e)
{
if (richTextBoxGuess .Text.Length <= 0) return;
string s = richTextBoxGuess.Text.Substring(0, 1);
if (s != s.ToUpper())
{
int curSelStart = richTextBoxGuess.SelectionStart;
int curSelLength = richTextBoxGuess.SelectionLength;
richTextBoxGuess.SelectionStart = 0;
richTextBoxGuess.SelectionLength = 1;
richTextBoxGuess.SelectedText = s.ToUpper();
richTextBoxGuess.SelectionStart = curSelStart;
richTextBoxGuess.SelectionLength = curSelLength;
}
}
Note that it doesn't not keep track of the changes and will not restore them when you keep adding at the front..
If you need culture invariance use the CultureInfo.CurrentCulture parameter of ToUpper()!
Check if the richTextBoxGuess is null or empty
if( richTextBoxGuess != ""){ // or different from null
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ){
//your code
}
}
Write this extension method:
public static string CapitalizeFirstLetter(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1);
}
And then use it as
richTextBoxGuess.Text = richTextBoxGuess.Text.CapitalizeFirstLetter();
private void _capitalizeFirstWord(Object sender, KeyPressEventArgs e)
{
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
}
If you want to capitalize every word
char _pre,_cur;
_pre=' ';
private void _capitalizeEveryWord(Object sender, KeyPressEventArgs e)
{
_cur = e.KeyChar;
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == ' ' && (!(_cur == _pre)) || e.KeyChar == '.' && (!(_pre == _cur)));
_pre=_cur
}
I want to validate a Textbox for a specific input pattern that contains Number, dot & plus singh only.
for example.
50.4+50.6+60.7+80.4
etc...
I want user can input only in this pattern because at last I want to plus this all value separated by plus singh. So it is necessary for a user that he follow this pattern.
please any body give me solution for this.
I am working in c# Windows form application.
Using a KeyPress event:
private void CheckInput(object sender, KeyPressEventArgs e)
{
// Make sure only digits, . and +
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '+')
{
e.Handled = true;
}
// Make sure . is in correct places only
else if (e.KeyChar == '.')
{
for (int i = textBox1.SelectionStart - 1; i >= 0; i--)
{
if (textBox1.Text[i] == '.')
{
e.Handled = true;
break;
}
else if (textBox1.Text[i] == '+') break;
}
}
// Make sure character before + is a digit
else if (e.KeyChar == '+'
&& !char.IsDigit(textBox1.Text[textBox1.SelectionStart - 1]))
{
e.Handled = true;
}
}
I created a textbox dynamically with a TextChangedEventArgs to restrict the textbox to enter only numbers and decimal point.
Following is the code in c#
const char Delete = (char)8;
if (Char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
else if (e.KeyChar == Delete)
{
e.Handled = false;
}
else if (e.KeyChar == '.')
{
if (!(amt.Text.Contains(".")))
e.Handled = false;
else
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
But I can't use this in wpf.
I tried to change the code with e.key or e.Text. But both these are not available. It is showing the following error Are u missing an assembly or directive.
Please anyone help me.
// one solution for filtering characters in a textbox.
// this is the PreviewKeyDown handler for a textbox named tbNumerical
// Need to add logic for cancelling repeated decimal point and minus sign
// or possible notation like 1.23e2 == 123
private void tbNumerical_PreviewKeyDown(object sender, KeyEventArgs e)
{
System.Windows.Input.Key k = e.Key;
// to see the key enums displayed, use a textbox or label
// someTextBox.Text = k.ToString();
// filter out control keys, not all are used, add more as needed
bool controlKeyIsDown = Keyboard.IsKeyDown(Key.LeftShift);
if (!controlKeyIsDown &&
Key.D0 <= k && k <= Key.D9 ||
Key.NumPad0 <= k && k <= Key.NumPad9 ||
k == Key.OemMinus || k == Key.Subtract ||
k == Key.Decimal || k == Key.OemPeriod) // or OemComma for european decimal point
else
{
e.Handled = true;
// just a little sound effect for wrong key pressed
System.Media.SystemSound ss = System.Media.SystemSounds.Beep;
ss.Play();
}
}
I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50.
I am using a code for adding .oo or .50 value at end of my value.
My code is
double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");
It is taking all the keys from keyboard, but I want to take only numbers and one . value.
Add a Control.KeyPress event handler for your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
You may do it through designer or in your constructor like this:
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?
Simplly in keyPress event of your textBox you could do this ...
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
try this one
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
// only allow one decimal point
if (e.KeyChar == '.'
&& textBox1.Text.IndexOf('.') > -1)
e.Handled = true;
}
try this code and just replace what you want input type 'validinpu' string.
try
{
short charCode = (short)Strings.Asc(e.KeyChar);
string validinput = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789 .";
if (Strings.InStr(validamt, Conversions.ToString(Strings.Chr(charCode)), Microsoft.VisualBasic.CompareMethod.Binary) == 0)
{
charCode = 0;
}
if (charCode == 0)
{
e.Handled = true;
}
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
// To disallow typing in the beginning writing
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Also try this short one
e.Handled = (!(e.KeyChar == (char)Keys.Back || e.KeyChar == '.')); //allow dot and Backspace
e.Handled = (e.KeyChar == '.' && TextBox1.Text.Contains(".")); //allow only one dot
this example only allow one dot and backspace
if (textBox.Text!="")
{
string txt = textBox.Text;
if (e.KeyChar.ToString().Any(Char.IsNumber) || e.KeyChar == '.')
{
textBox.Text = rate;
}
else
{
MessageBox.Show("Number Only", "Warning");
textBox.Text = "";
}
}
My tested code
if(e.KeyChar.Equals('\b'))
{
e.Handled = false;
}
else
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
else
// only allow one decimal point
if (e.KeyChar == '.'
&& textBox1.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
I'm trying to set a hex mask for a textbox. So that only valid hex numbers can be entered. (And ',' and 'ENTER')
It almost works. So far it will only allow small letters from a-f and numbers 0-9, but I can still enter capital letters GHIJKLM. (At first, when program is started it seems to accept one char ex k, but after it has excepted k once it wont be shown after that, until next time you start the program. That's weird.)
Here is a part of code:
private void EnterKey(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// if keychar == 13 is the same as check for if <ENTER> was pressed
if (e.KeyChar == (char)13)
{
// is <ENTER> pressed, send button_click
button1_Click(sender, e);
}
{
// this will only allow valid hex values [0-9][a-f][A-F] to be entered. See ASCII table
char c = e.KeyChar;
if (c != '\b' && !((c <= 0x66 && c >= 61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39) || (c == 0x2c)))
{
e.Handled = true;
}
}
}
This is how I bind the event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyDown);
}
Could anyone of you wise guys, see what I'm doing wrong?
It's my first small program, so go easy on me :o)
This:
c <= 0x66 && c >= 61
Should be:
c <= 0x66 && c >= 0x61 //hex literal
Note that you're wasting valuable time by looking up hex codes, you can easily compare characters:
if ((c >= 'a') && (c <= 'f'))
As for the first character: you shouldn't bind the KeyPress at the TextChanged event - it is too late! Here's the sequence of events:
Form Loads
...
User click on a key.
TextChanged triggered, changing the text and binding the event.
User click on a key.
KeyPress triggered.
What you want to do is to bind the event right from the start. The best place is the Form_Load event.
You can also use the Properties window to bind the event at design time
If you had not used magic numbers, you would never have run into this problem. Rewrite your if like this:
if (!(c == '\b' || ('0' <= c && c <= '9') || ('A' <= c && c <= 'F') // et cetera
Use a regular expression:
using System.Text.RegularExpressions;
...
if (!(Regex.IsMatch(e.KeyChar.ToString(), "^[0-9a-fA-F]+$"))
e.Handled = true;
What type of program is this an ASP.NET website or some type of winforms/wpf thick client? The reason I ask is that you may be testing on stale code. Otherwise on change can be to just flip the checking logic to be more aligned with what you want. Ensuring that the entered character is one element in the allowed set. A refactoring is below.
e.Handled = (c >= 0x61 && c <=0x66) || (c >=0x41 && c<= 0x46) || (c >= 0x30 && c <= 0x39);
As an alternative approach if you just want to validate the whole textbox at one time instead of after each key press you can just parse the value to see if it is a number. The following code fragment will generate parse the value 11486525 from AF453d. If the number is not a valid hex value then the result of isHex will be false;
int i;
string s = "AF453d";
bool isHex;
isHex = int.TryParse(s, System.Globalization.NumberStyles.AllowHexSpecifier, null, out i);
Console.WriteLine(isHex);
Console.WriteLine(i);
Why complicate it?
private void EnterKey(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
char c = e.KeyChar;
e.Handled = !System.Uri.IsHexDigit(e.KeyChar) && c != 0x2C;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
/* less than 0 or greater than 9, and
* less than a or greater than f, and
* less than A or greater than F, and
* not backspace, and
* not delete or decimal (which is the same key as delete). */
if (
((e.KeyChar < 48) || (e.KeyChar > 57)) &&
((e.KeyChar < 65) || (e.KeyChar > 70)) &&
((e.KeyChar < 97) || (e.KeyChar > 102)) &&
(e.KeyChar != (char)Keys.Back) &&
((e.KeyChar != (char)Keys.Delete) || (e.KeyChar == '.'))
) e.Handled = true;
}
Based on the answer by Kobi for WPF
private void EnterKey(Object sender, KeyEventArgs e)
{
Key c = e.Key;
if (!((c >= Key.A) && (c <= Key.F)))
{
if (!((c >= Key.D0) && (c <= Key.D9)))
{
if (!((c >= Key.NumPad0) && (c <= Key.NumPad9)))
{
e.Handled = true;
LogText("Handled");
}
}
}
}
Captures letters, numbers and keypad numbers.