I want to return to previous form in C# using backspace key.
I am using KeyDown event on form to check for backspace key . but the form is not detecting any key down event.
How can I achieve this?
private void History_P_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData.ToString() == "Back")
MessageBox.Show("Back button pressed");
}
where History_P is form name.
You need to enable the KeyPreview property on the Form.
With this property the key being pressed (all KeyUp, KeyDown, KeyPressed events) will first be caught by the Form and is then passed on to the control that is focused at that moment, unless you set the KeyPressEventArgs.Handled to true.
Related
Here is code for a form with a button(not shown) and a textbox. Pressing any key other than function keys causes the KeyDown Event to fire as expected, the textbox is selected, the cursor flashes and the character of the subsequent keystroke appears in the textbox. When pressing a function key however, although the textbox is selected, the cursor does not flash and the character of the very next keystroke does not appear in the textbox. The characters of subsequent keystrokes do appear as expected.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
textBox1.Select();
}
}
I have been able to circumvent this problem by overriding the ProcessCmdKey method but I am curious to know how to do it with KeyDown.
Thanks!!
These days, the preferred method of reading F[1-12] key presses is to override the ProcessCmdKey method, as you said. However, one (now deprecated) way to allow KeyDown to handle F keys is to set the form's KeyPreview property to true. However, as you can see in this post, there are disadvantages to this approach, so it's safer to use ProcessCmdKey.
In my Windows application, I made a multiline textbox by setting AcceptsReturn property to True. It lets the user enter multiple lines of text into the textbox. Also, I'd like to do something every time, the Return/Enter key is pressed in the textbox. The event handler code is as follows...
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
// do something here
}
It appears that, if AcceptsReturn is set to True and the Return key is pressed, this event handler is not called at all. Any other key press is detected properly. If AcceptsReturn is not set to True and the Return key is pressed, the event handler is called and Return key press is detected just fine. The problem with this is that pressing Return key doesn't advance the user to the new line in the textbox (as expected).
So, I'd like the Return key press to properly advance the user to the new line in the textbox as well as I'd like to be able to detect that Return key press. Is my approach wrong? Is there a better way to do this?
KeyDown is bubbling event, which means it is first raised on the source control (the TextBox), then on the parent, then on the parent's parent, and so on, until it is handled. When you set AcceptsReturn to true, the control handles the Return key, so the event is not bubbled. In this case you can use the tunneling version of the event: PreviewKeyDown, which is raised on each ancestor of the control from the top to the bottom before it reaches the source control.
See Routing Strategies on MSDN
I'm currently stumped. I can't seem to get the KeyEvent to work. Simple code like this just won't respond to the key I'm pressing. I've tried KeyDown and KeyPress. No errors while compiling... what is causing this?? It will just let me enter the E key without prompting the MEssage box.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.E)
{
MessageBox.Show("E");
}
}
I think you should be using the PreviewKeyDown Event, for example, instead of the standard key events, as sometimes these events are blocked an not bubbled up through the control.
You should change the Form KeyPreview property to true where textbox1 is located.
Normally when pressing the TAB key you change the focus to the next control in the given tab order. I would like to prevent that and have the TAB key do something else. In my case I'd like to change focus from a combobox to a completely different control. I can't do this by setting the tab order. I need to do this programatically. Any idea how? It seems like the KeyDown and KeyPress events can't handle TAB key correctly.
Thanks.
Override ProcessDialogKey or ProcessTabKey on your Form and do the logic you want depending on which control is focused.
Based on JRS's suggestion of using the PreviewKeyDown event, this sends the key press through to the control:
private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Tab)
e.IsInputKey = true;
}
Then you can handle the control's KeyDown event if you want to customise the behaviour:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
MessageBox.Show("The tab key was pressed while holding these modifier keys: "
+ e.Modifiers.ToString());
}
}
TextBoxBase alternative
If the control is derived from TextBoxBase (i.e. TextBox or RichTextBox), with the Multiline property set to true, then you can simply set the AcceptsTab property to true.
TextBoxBase.AcceptsTab Property
Gets or sets a value indicating whether pressing the TAB key in a multiline text box control types a TAB character in the control instead of moving the focus to the next control in the tab order.
Override the control's LostFocus event see link below for examples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx
Since I am building a UserControl, I ended up using the PreviewKeyDown event on the control. This avoids having to handle key press events on the host form.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
You can try this code on your KeyDown event:
if (e.KeyCode == Keys.Tab) {
//your logic
e.SuppressKeyPress = true;
}
If the button clicked is Tab, then do any custom logic you want, then call SuppressKeyPress to stop the KeyPress event from firing and invoking the normal Tab logic for you.
How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?
If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.
Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}
You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control.
See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.)
As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.
You can subscribe to the KeyUp event of the TextBox.
private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DoSomething();
}
The Form has a KeyPreview property that you can use to intercept the keypress.
Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.
Simply use
this.Form.DefaultButton = MyButton.UniqueID;
**Put your button id in place of 'MyButton'.
if (e.KeyCode.ToString() == "Return")
{
//do something
}