Change textBox.text to any key pressed - c#

I'm trying to when a user presses a key in the textBox the textBox will show the key the user pressed so i can save it as a variable and use it elsewhere.
Right now i have this and this works
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.A)
{
textBox.Text = "A";
}
}
But it's limited to the A key is there any way to make it any key?

You can convert the KeyEventArgs e.KeyCode to a char.
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
Char ch = (Char)e.KeyCode;
textBox.Text = ch.ToString();
}
EDIT: Forgot this is WPF which doesn't support KeyEventArgs.KeyCode
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
textBox.Text = e.Key.ToString();
}
This will give you the things like CapsLock and Shift etc, but, in the
case of the alphanumeric keys, it won't be able to tell you the state
of shift etc. at the time, so you'll have to figure that out yourself.
The second alternative is to use the TextInput event instead, where
e.Text will contain the actual text entered. This will give you the
correct character for alphanumeric keys, but it won't give you control
characters.
Reference: https://stackoverflow.com/a/486967/6138713

Related

C# Detect when key gets pressed and trigger a button

So I'm trying to make a simple calculator. The user can only input the numbers by the buttons on the form or by the numpad. This is the code I have:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
string key = "";
switch (e.KeyCode)
{
case (Keys.NumPad1):
key = "1";
break;
case (Keys.NumPad2):
key = "2";
break;
default:
break;
}
txt_string.Text = txt_string.Text + key;
}
If I make a breakpoint on the KeyDown function and press the Numpad keys (and every other keys) the program doesnt even comes to that breakpoint.
Do I have to change something on my Form to detect the Keys?
You'll need to set KeyPreview to true (property on the form). Also, I would advise against trying to debug the behaviour - because you may affect the behaviour you're testing (Debug.WriteLine()) is your friend here.
Just to point out that many keyboard doesnt have numpad. You can check if the key is a integer.
void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
txt_string.Text += e.KeyChar;
}
}
This is more a Code Review than a solution though.

How to make TextBox to receive only number key values using KeyDown Event in C#?

This code in my form updates the textBox1.Text twice whenever number keys are pressed.
private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
//MessageBox.Show();
if( char.IsNumber((char)e.KeyCode) ) {
textBox1.Text += (char)e.KeyCode;
}
}
Explain why if you can?
Modify the code or provide me a better solution for this.
Input ( in textbox1 ):
54321
Output:
1234554321
When you press a key, a character is already appended to your TextBox. Then you run the following code and, if the key represents a number, you append it again:
if (char.IsNumber((char)e.KeyCode)) {
textBox1.Text += (char)e.KeyCode;
}
If you want to suppress any key that's not a number, you could use this instead:
e.SuppressKeyPress = !char.IsNumber((char)e.KeyCode);
From the syntax I assume you are using WinForms for the following answer.
The key pressed event is not suppressed, so it still works like a normal key pressed event and adds the character to the text of the box. Additionally you add the character to the text yourself once again.
Try to suppress the key pressed event in case a key is pressed, you do not want to allow.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!char.IsNumber((char)e.KeyCode))
{
e.SuppressKeyPress = true;
}
}
You can try like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
}
Check New keyboard APIs: KeyEventArgs.SuppressKeyPress
The problem is that "Handled" doesn't take care of pending WM_CHAR
messages already built up in the message queue - so setting Handled =
true does not prevent a KeyPress from occurring.
In order not to break anyone who has currently got e.Handled =
true, we needed to add a new property called SuppressKeyChar. If we
went the other way, if "handling" a keydown suddenly started to
actually work, we might break folks who accidentally had this set to
true.
Try this code to accept numbers only
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
e.Handled = true;
}

KeyEventArgs in C#

I have a problem to how to catch which key is pressed. This is my code, but i cant get what key was pressed. I'm using KeyEventArgs for declaration of new variable and then comparing it.
private void textBox2_TextChanged(object sender, EventArgs e)
{
KeyEventArgs k = null;
if (e is KeyEventArgs)
{
k = (KeyEventArgs)e;
}
if (k.KeyCode == Keys.Enter)
{
// do something here
}
}
You need to add:
[component_name].KeyDown += new System.Windows.Forms.KeyEventHandler(this.Key_Pressed_Method);
into the constructor of your Form. Then, you can define what you want to do in Key_Pressed_Method() method.
TextChanged won't give you a KeyEventArgs. You want KeyUp, KeyDown or KeyPress instead. KeyPress gives you KeyPressEventArgs instead.

how cancel label edit with escape key and return the label to what it was

In Windows Form controls like listview and treeview, when someone edit the label of an item an then press the "Escape" key, the edition end but the node remains with whatever i write in it. I want in exchange that when i press the Escape key the label return to what it was. I know that i must take the label before the label edit precisely in the "BeforeLabelEdit" event. In the "KeyPress" event handler i don't know how to stop the label edition. How can i do that?
Update
i found the method that i thought that doesn't exist, but now the problem is other. The Escape key press appears to be unchatchable in the middle of an edition label action.
private void ObjectWithItems_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (treeViewDocXml.SelectedNode != null)
{
treeViewDocXml.SelectedNode.EndEdit(true);
}
}
}
ok, I'am not sure what you talking about, but here is example how to cancel text box editing and set text before editing started:
string textBefore;
private void textBox1_Enter(object sender, EventArgs e)
{
textBefore = textBox1.Text;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char)Keys.Escape)
textBox1.Text = textBefore;
}
Hope it helps.

C# Textbox Keypress Control Help

I have a standard textbox that I want to perform an action on a keypress. I have this code currently:
private void idTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter/Return)
{
e.Handled = true;
SearchButtonClick(sender, EventArgs.Empty);
}
}
The problem is, I have tried both Enter and Return up there which is the reason for that. It is only firing that check for normal keys that are not like shift, control, etc. How can I design this so that it will pick up and use the enter/return key in the same way?
You should use the KeyDown event instead:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
//...
}
}
If it for some reason has to be KeyPress, you can use (char)13 or '\r' for your check, though I doubt that would work well on a non-Windows OS.
if (e.KeyChar == '\r')
You cannot just cast Keys.Return to a char, because it's a bitflag enum and doesn't just hold the corresponding ASCII code.
Use the KeyDown event instead.

Categories