Using backspace to move back to previous textBox (C#) - c#

This may be a simple question. I'm new to C# (and most programming) and I am trying to make a program that consists of two text boxes. The information in these textboxes will frequently be deleted and new information will need entered, so it needs to be quick. For convenience I'm trying to make the backspace key refocus on the previous textbox rather than using Shift+Space or clicking. Here is what I have. The program runs, but the code below doesn't seem to do what I intend it to do.
if (e.KeyCode == Keys.Back && textBox2.TextLength == 0)
textBox1.Focus();
So, when textbox2 has 0 characters and backspace is subsequently keyed, I would like it to move back to textbox1. Thanks for any help.

So to make this work you're going to need to make sure you run this code on KeyUp, but you also do not need multiple KeyUp handlers to do this. Consider this KeyUp handler:
private void textBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) { return; }
if (e.KeyCode == Keys.Back && textBox.Text.Length == 0)
{
// this here of course being the Form
// Select causes the form to select the previous control in the tab order
this.Select(true, false);
}
}
Now just attach this handler to all text boxes that you want to behave this way and they'll all work.

I did get it to work finally. What I did wasn't too different than what I was trying before, but here is how I did it.
I created two text boxes from the .cs [Design] view.
I selected each box and clicked the "Events" lightning bolt icon under Properties. This is something I left out previously when this didn't work.
I set both of them to KeyPress and TextChanged (i.e. textBox1_KeyPress & textBox1_TextChanged (Did the same thing with textBox2). I don't know if this is part of the reason why it worked. I'm just documenting my actions.
I double clicked each textBox, which created an EventArgs for each. This is where I stored my regular code.
In addition to the EventArgs I manually created a KeyEventArgs (see below) where I put the function for the Backspace. Here is the code:
// Here is the KeyEventArgs I created using KeyPress (Public).
public void textBox2_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back && textBox2.Text.Length == 0)
textBox1.Focus();
}
// Here is where the rest of my code (Private).
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "A")
richTextBox3.Text = "January";
if (textBox2.Text == "B")
richTextBox3.Text = "February";
if (textBox2.Text == "C")
richTextBox3.Text = "March";
// Code Continues...
Sorry if this isn't clear. I just wanted to document what I did in case it helps someone later. Thanks for the help everyone.

Related

Forms, basic calculator key triggering problem

private void UserInputText_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.D4 && e.Modifiers == Keys.Shift) || (e.KeyCode == Keys.Add))
{
if (String.IsNullOrEmpty(UserInputText.Text))
{
MessageBox.Show("Bir sayı giriniz.");
UserInputText.Clear();
return;
}
if (double.TryParse(UserInputText.Text, out sayı1))
{
CalculationResultText.Text = sayı1 + " + ";
islem = "+";
UserInputText.Clear();
}
else
{
MessageBox.Show("Sadece sayı değeri girebilirsiniz.");
UserInputText.Clear();
}
}
}
I am coding a basic forms calculator. I am trying to trigger addition function and clear the textbox when textbox is focused and user presses "+" key. "if (String.IsNullOrEmpty(UserInputText.Text)) and else conditions work well. But if no Message boxes shows up as in the
if (double.TryParse(UserInputText.Text, out sayı1)) condition, the "+" character remains in the textbox as in the image. Thanks for help.
If I understand correctly, you want to first check the character that was typed in and if it's incorrect then you want to prevent this character from appearing?
If so, then you need to set e.Handled = true property when you want to prevent it.
This call tells the GUI element (your TextBox) that "I did all the checks for this event (i.e. KeyDown event), and I don't want you to contribute in handling of this event (i.e. normally the TextBox would try to add this character to its Text property, but you prevent it)".
Check out documentation on KeyEventArgs.Handled.
KeyPress event enables you to prevent any further changes in the TextBox.
You can do that thanks to Handled property of KeyPressEventArgs
private void UserInputText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
UserInputText.Clear();
e.Handled = true;
}
}

How to make keyboard shortcuts to button click

I am doing my graduation work and I need a little help.
So far I've done most of my work and now I need someone to help me with the shortcuts.
This is how my work looks like (for now):
I need to make shortcuts for those buttons so that user doesn't have to click on button with mouse. I wish to make it possible that when user presses F1 on the keybord - it's like he pressed button1 with mouse. F2 stands for button2 and so on.
Shortcuts as CTRL+ some key are also acceptable. I only need example how to make couple buttons, and i will make others :)
Thanks
Set Form1's KeyPreview-property to true in the designer or in the code:
this.KeyPreview = true;
Then add KeyUp-action to your form, which accepts all keys (even Delete etc):
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
button1ClickMethod();
}
}
Then separate your buttons' actions to individual methods, like button1ClickMethod(), and avoid using the Button1_Click(null, null);. Call this button1ClickMethod() in the KeyUp-event when a desired key is up.
To use combinations, you can use this:
// If CTRL and F1 were pressed
if (e.Control && e.KeyCode == Keys.F1)
{
MessageBox.Show("Shortcut CTRL + F1 was pressed!");
}
You can also check if the Shift was pressed at the same time with e.Shift-property, same way like the e.Control.
KeyPress event will help you
Sample code ;
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
//Call the event according to key
// if(e.KeyChar == "")
//btnSave_Click(null,null)
}

keydown to correspond with button down

Hello I am trying to match the button down visual (on the WinForm, the button boarder gets a little darker, indicating it is pressed) with a keydown event. First of all I need to detect a keydown for numbers only. Then when the key goes down, the corresponding number button on the form should look like it is depressed as well. Sorry if this is already been answered using differt jargon. I already know how to perform a button click with the keydown.
Make a test code on KeyDown event. Write down the keyboard codes you shall see from pressing 0 to 9. Then use those keyboard codes in your KeyDown's if statement
You can use a Checkbox and set the appearance to be Button. Then you can do something like this:
private void OnKeyDown(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = true;
}
private void OnKeyUp(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = false;
}
As far as the Keys, you can just use the KeyEventArgs.KeyCode
e.KeyCode == Keys.D0 || .. || e.KeyCode == Keys.D9

c# Listbox control (arrows and enter keys)

I have a listbox which displays the contents of an array. The array is populated with a list of results when my "go" button is pressed.
The go button is set as the AcceptButton on the form properties so pressing the Enter key anywhere in the focus of the form re-runs the go button process.
Double clicking on a result from the array within the listbox works fine using below:
void ListBox1_DoubleClick(object sender, EventArgs e) {}
I would like to be able to use my arrow keys and enter keys to select and run an event without having to double click on the line within the listbox. (however go button runs each time instead)
Basically open the form, type search string, press enter to run go button, use up and down arrows then press enter on selection to run same event as double click above. Will need to change focus after each bit.
You can handle the KeyDown events for the controls you want to override. For example,
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//execute go button method
GoButtonMethod();
//or if it's an event handler (should be a method)
GoButton_Click(null,null);
}
}
That will perform the search. You can then focus your listbox
myListBox.Focus();
//you might need to select one value to allow arrow keys
myListBox.SelectedIndex = 0;
You can handle the Enter button in the ListBox the same way as the TextBox above and call the DoubleClick event.
This problem is similar to -
Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox
Certain controls do not recognize some keys when they are pressed in Control::KeyDown event. For e.g. list box does not recognize if the key pressed is Enter key.
See the remarks section of the Control::KeyDown event reference.
One way to resolve your problem might be writing a method for the Control::PreviewKeyDown event for your list box control:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && this.listBox1.SelectedIndex - 1 > -1)
{
//listBox1.SelectedIndex--;
}
if (e.KeyCode == Keys.Down && this.listBox1.SelectedIndex + 1 < this.listBox1.Items.Count)
{
//listBox1.SelectedIndex++;
}
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}

Detect Key in KeyUp event

I have a textbox on a form where I'm trying to detect the keys the user types in. The TextBox is multilined with wordwrap on. I don't want the user the press the enter key (as I want all text entered on ONE line, wrapped) so I used the following code:
private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char)13) {
MessageBox.Show("Enter keys are not allowed");
e.KeyChar = (char)0;
}
}
This worked fine in my tests, but when I tested for CTRL+ENTER it didn't work as I'm not sure how to detect for the control key. From my googling I found that I need to use the KeyUp/Down events so I now have the following Code:
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
}
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
The problem with the KeyUp/Down event is that I don't know how to REMOVE the enter key from the text - unlike the KeyPress event when I can set the KeyChar to zero. The event captures both the Enter and Ctrl+Enter keys, but the cursor still goes to the next line in the TextBox.
Thanks for any help on this.
Hmm, there's no reason to disallow the Enter key by handling the KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the textbox control to False. This will prevent a multiline textbox from responding to a press of the Enter key.
Of course, this doesn't solve the problem of Ctrl+Enter. In fact, that's the expected way to create a new line when the AcceptsReturn property is set to False. To solve that, you will need to handle one of the keyboard events and prevent the control from receiving this input.
KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. That will catch them no matter which other modifier key they might be combined with. Then, once you've found an Enter keypress, you want to set the e.Handled property to True in order to prevent it from being passed on to the control.
But unfortunately, we're not quite done yet. The textbox control tries to handle certain keys internally, and you're not going to be able to override that in a key event handler method. You also need to tell the control not to interpret that particular key as an input key. There are two primary ways of doing this. The first (and recommended way) is to inherit from the base TextBox class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is just to handle the PreviewKeyDown event, and set the IsInputKey property to False.
Sample code:
private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Set the IsInputKey property to False
e.IsInputKey = false;
}
}
private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Show the user a message
MessageBox.Show("Enter keys are not allowed in this textbox.");
// Prevent the key event from being passed on to the control
e.Handled = true;
}
}
And, though I assume this is for testing purposes only, you definitely want to take that MessageBox call out of there for production code. Find another way to alert the user that their input was not allowed, such as a short beep sound and an ErrorProvider component placed next to the textbox. Showing a message box is very jarring, and not very user-friendly. See my answer here for other hints and tips.
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
// mark event as handled
e.Handled = true;
}
}
from msdnlink
edit:
I think that you need the key down event not the key up
EDIT2
here is some tested code and it works as you wanted:
bool invalid=false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
invalid = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (invalid)
{
e.Handled = true;
}
invalid = false;
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
You wanted to detect Ctrl + Enter.
if (e.KeyData == (Keys.Control | Keys.Enter)) {..
Keys.Control and Key.Enter are nothing but are some values please refer . Now doing logical or will not necessarily result to key which has been pressed. Totally illogical clause.
Ok now come to your actual problem you want to detect Enter stroke and Ctrl + Enter stroke to be treated as same.
Besides you want to undo the newline character thats been introduced. Try
PreviewKeyDown or Preview key up eventhandler with the following condition
if(e.KeyCode==Keys.Enter)
Let me know if this works

Categories

Resources