i want to set focus from one textbox1 to another textbox2 while i am pressing ENTER key in textbox1 in C# windows application(c# 2005)
First, you will have to set the KeyPreview property of the Form set to true. Then you will have to override the form's OnKeyDown method and make a case like:
if(e.KeyCode == Keys.Enter)
{
Control ctlNext = this.GetNextControl(this.ActiveControl, true);
ctlNext.Focus();
}
else
{
base.OnKeyDown(e);
}
Mind you that this code will work for every control on the form, and move the focus to the next one. If you just want this code to work for the textboxes you could add a check like:
if(this.ActiveControl is TextBox)
{
...
}
add this to your form
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Control NextControl = this.GetNextControl(this.ActiveControl, true);
while (!NextControl.TabStop || !NextControl.Enabled || !NextControl.Visible)
{
NextControl=this.GetNextControl(NextControl, true);
}
NextControl.Focus();
}
else
{
base.OnKeyDown(e);
}
}
Handle the KeyPress or KeyDown event of textbox1 and then call textbox2.Focus().
Related
In my UWP application, I want my TextBox to be able to go to new line by pressing down the Enter key but I also need to trigger an action when Ctrl+Enter are pressed.
The issue is, I can't seem to find a way to prevent the text to go to the next line when I press down Ctrl+Enter. Here is the code I have tried.
XAML
<TextBox x:Name="TextBox1" AcceptsReturn="True" />
In the constructor
TextBox1.AddHandler(KeyDownEvent, new KeyEventHandler(TextBox1_KeyDown), true);
Handler
private void TextBox1_KeyDown(object sender, KeyRoutedEventArgs e)
{
var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control);
if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && e.Key == VirtualKey.Enter)
{
e.Handled = true;
}
}
You could create a custom class that inherits from TextBox and override its OnKeyDown method where you have full control of firing the base.OnKeyDown method to prevent from adding a new line.
class CTRLEnterTextBox : TextBox
{
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down) && e.Key == VirtualKey.Enter)
{
e.Handled = true;
}
else
{
base.OnKeyDown(e);
}
}
}
I have a form with CancelButton and AcceptButton (named btnCancel and btnOK). And I have some ComboBoxes as input fields.
ComboBoxes prevent my AcceptButton and CancelButton to receive Escape and Enter keys, so I added this code to KeyDown event for all fields:
if (e.KeyData == Keys.Escape)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnCancel.PerformClick();
}
}
else if (e.KeyData == Keys.Enter)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnOK.PerformClick();
}
}
This is the code in Clicked event of OK button:
if (!changesAreSaved)
{
SaveChangesToNode();
}
List<int> invalidIndices = ValidateAndRefineNodes(true);
if (invalidIndices.Count == 0)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show(this, "Enter correct values for all fields before you press OK.", "Cannot Save Information",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Everything is OK but when a ComboBox has Focus and I press Enter key on my keyboard, btnOK_Clicked calls Fields_KeyDown again only when it shows its MessageBox (on else part of if). Exactly right after MessageBox.Show(...) is being called, KeyDown event is being called for second time without any reason.
This is Call Stack for first call:
And this is for second:
Second call should not occur at all. In second Call Stack, first btnOK_Click (third line) again calls Fields_KeyDown (second line) from MessageBox.Show(...). How is this possible? I'm confused...
Call Stack for second call with External Code visible:
You cannot correctly process Escape and Enter key in KeyDown event because they are handled during the keyboard preprocessing phase - Control.IsInputKey and Control.ProcessDialogKey. Normally controls do that for you, but looks like there is a bug in ComboBox implementation when DropDownStyle is Simple.
To get the desired behavior, create and use your own ComboBox subclass like this
public class MyComboBox : ComboBox
{
protected override bool IsInputKey(Keys keyData)
{
if (DropDownStyle == ComboBoxStyle.Simple)
{
switch (keyData & (Keys.KeyCode | Keys.Alt))
{
case Keys.Return:
case Keys.Escape:
return false;
}
}
return base.IsInputKey(keyData);
}
}
P.S. And of course don't forget to remove your KeyDown event handlers.
While I have no idea about the main reason behind this behavior.
But in this situation obviously KeyDown event triggers 2 times. (Set a breakpoint and you will see.)
Since you need to handle it in code, You can try this to neglect one of Enter keys:
bool handled = true;
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
/*Prevent handling the Enter key twice*/
handled = !handled;
if(handled)
return;
//Rest of logic
//OkButton.PerformClick();
}
}
I have a form with CancelButton and AcceptButton (named btnCancel and btnOK). And I have some ComboBoxes as input fields.
ComboBoxes prevent my AcceptButton and CancelButton to receive Escape and Enter keys, so I added this code to KeyDown event for all fields:
if (e.KeyData == Keys.Escape)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnCancel.PerformClick();
}
}
else if (e.KeyData == Keys.Enter)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnOK.PerformClick();
}
}
This is the code in Clicked event of OK button:
if (!changesAreSaved)
{
SaveChangesToNode();
}
List<int> invalidIndices = ValidateAndRefineNodes(true);
if (invalidIndices.Count == 0)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show(this, "Enter correct values for all fields before you press OK.", "Cannot Save Information",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Everything is OK but when a ComboBox has Focus and I press Enter key on my keyboard, btnOK_Clicked calls Fields_KeyDown again only when it shows its MessageBox (on else part of if). Exactly right after MessageBox.Show(...) is being called, KeyDown event is being called for second time without any reason.
This is Call Stack for first call:
And this is for second:
Second call should not occur at all. In second Call Stack, first btnOK_Click (third line) again calls Fields_KeyDown (second line) from MessageBox.Show(...). How is this possible? I'm confused...
Call Stack for second call with External Code visible:
You cannot correctly process Escape and Enter key in KeyDown event because they are handled during the keyboard preprocessing phase - Control.IsInputKey and Control.ProcessDialogKey. Normally controls do that for you, but looks like there is a bug in ComboBox implementation when DropDownStyle is Simple.
To get the desired behavior, create and use your own ComboBox subclass like this
public class MyComboBox : ComboBox
{
protected override bool IsInputKey(Keys keyData)
{
if (DropDownStyle == ComboBoxStyle.Simple)
{
switch (keyData & (Keys.KeyCode | Keys.Alt))
{
case Keys.Return:
case Keys.Escape:
return false;
}
}
return base.IsInputKey(keyData);
}
}
P.S. And of course don't forget to remove your KeyDown event handlers.
While I have no idea about the main reason behind this behavior.
But in this situation obviously KeyDown event triggers 2 times. (Set a breakpoint and you will see.)
Since you need to handle it in code, You can try this to neglect one of Enter keys:
bool handled = true;
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
/*Prevent handling the Enter key twice*/
handled = !handled;
if(handled)
return;
//Rest of logic
//OkButton.PerformClick();
}
}
This question already has answers here:
Windows Forms - Enter keypress activates submit button?
(9 answers)
Closed 8 years ago.
I have a TextBox and a button. In TextBox I want to type text and then be able to click enter and press my button. When I press button I can redirect to text box by using button1.Focus();
Now if I type text and press enter nothing happens. I can use tab to switch to a button, but I just wonder if I can just press enter instead.
Any ideas?
A simple solution would be:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click!");
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button1_Click(textBox1, new EventArgs());
}
If you are using this in more than one place I'd recommend creating a user control containing the TextBox and the Button in order to encapsulate this behavior.
In the properties of your form, set the button as the value for the AcceptButton property.
You can add a KeyPressed event to your textbox. Inside this event check if the key pressed is enter, and if it is, call the button's click event.
I think this way is a quite clever routine for your problem. This procedure allows you to check for TAB press as well. It is by the way snipped directly from:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputkey.aspx
You're right on by simply changing the Keys.Tab in the microsoft sample to Key.Enter. Remember that when this textbox is used in conjunction with AutoComplete routines, it could be convenient to instantiate it outside the constructor or in a constructor overload. Here is what the instantiation of the textbox look like:
ReturnTextBox returntextbox = new ReturnTextBox();
using System.Windows.Forms;
public class Form1 : Form
{
public Form1()
{
FlowLayoutPanel panel = new FlowLayoutPanel();
ReturnTextBox returntextbox = new ReturnTextBox();
returntextbox.Text = "returntextbox";
panel.Controls.Add(returntextbox);
TextBox textBox1 = new TextBox();
textBox1.Text = "Normal TextBox";
panel.Controls.Add(textBox1);
this.Controls.Add(panel);
}
}
class ReturnTextBox : TextBox
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
return true;
}
else
{
return base.IsInputKey(keyData);
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
this.SelectedText = " ";
}
else
{
base.OnKeyDown(e);
}
}
}
Hi i have a C# winform application with a particular form populated with a number of textboxes. I would like to make it so that by pressing the right arrow key this mimicks the same behaivour as pressing the tab key. Im not really sure how to do this.
I dont want to change the behaivour of the tab key at all, just get the right arrow key to do the same thing whilst on that form.
Can anyone offer any suggestions?
You should override the OnKeyUp method in your form to do this...
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
Control activeControl = this.ActiveControl;
if(activeControl == null)
{
activeControl = this;
}
this.SelectNextControl(activeControl, true, true, true, true);
e.Handled = true;
}
base.OnKeyUp(e);
}
You can use the KeyDown event on the form to trap the key stroke then perform whatever action you want. For example:
private void MyForm_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Right)
{
this.SelectNextControl(....);
e.Handled = true;
}
}
Don't forget to set the KeyPreview property on the form to True.
I think this will accomplish what you're asking:
private void form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
Control activeControl = form1.ActiveControl;
// may need to check for null activeControl
form1.SelectNextControl(activeControl, true, true, true, true);
}
}