Reputation: 3959
In C#, how can I capture all char
typed into a textbox
as the user types?
So if a user typed Hello World
the function would capture each individual char
and process it.
I need super exact control of all text as it comes in. I will delete from the textbox
all invalid characters, and will allow the user to stack up certain characters and then some other character when they are used will fire of functions.
Example:
The user types the following into a textbox
Blarg Blarg 600*50-90blarg
This is how I want to operate this mess:
As each Char gets read, All alphabetic characters are discarded from memory and from the textbox, so that the user does not even see them entered.
So the first part doesn't even show up, then when the user types 6
that sticks to the textbox, and then 0
and then 0
so eventually what is displayed to the user is 600
. Then the user types *
and this is discarded from the screen but its causes a function to fire that takes the number in the textbox and awaits the next digit.
I can handle most of this but validating user input from the keyboard is not easy in C#
So the question: Can I operate code on each char as they come right of the keys?
Upvotes: 1
Views: 1776
Reputation: 17544
If you are only using your textbox to allow only particluar chars as input, you can try using a MaskedTextBox
.
Upvotes: 1
Reputation: 7475
Simple, you use the KeyPress event like so:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
// your code here
}
You could then parse the char info like so:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (c >= 48 && c <= 57)
{
// numeric value
// do something
}
else if (c == 42)
{
// multiply (*)
// do something
}
else if (c == 47)
{
// divide (/)
// do something
}
else if (c == 13)
{
// enter key
// do something
}
else
{
// discard
e.Handled = true;
}
}
Upvotes: 4