I currently have the following event handler which catches the Ctrl+Enter key combo in my Form code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
}
}
I also have two non-ReadOnly TextBoxes in the form, one of which is multiline, while the other one isn't. Whenever I hit Ctrl+Enter, the event does get handled, but it also registers as an Enter keypress when the focus is in either TextBox. What I want to do is register the key combo without the Enter keypress modifying the text in either box. Is there any way I could go about doing this?
Your best choice is use ProcessCmdKey: Just add this to your Form add it will work:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.Enter))
{
// Stuff
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
You should use the PreviewKeyDown event instead and set the IsInputKey property accordingly:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
e.IsInputKey = false;
}
}
UPDATE: From the name of your handler, I guess you added it to the Form's KeyPress/KeyDown/PreviewKeyDown event. Instead you should register the method I showed above with each TextBox's PreviewKeyDown event.
To not destroy what already works for you, you may leave your code as it is and just add a handler to the TextBox's PreviewKeyDown event where you set IsInputKey to false for the specified keys, but don't do your // Stuff.
Related
I am trying to disable tab key from datagridview, also to create my own event on it. Also if it is possible to disable up,down,right,left and enter key.
OnLoad Event
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
On KeyDownEvent
private void gridInvoice_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
//SelectNextControl(dataGridView1, true, true, true, true);
// or Parent.SelectNextControl() if the grid is an only child, etc.
e.Handled = true;
}
}
With code above tab key it works. I moves to next cell. How can i prevent this?
You have to use PreviewKeyDown event instead of KeyDown.
According to Microsoft Control.PreviewKeyDown Event Description
Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses.
You need to insert the code below in PreviewKeyDown event if you want to use KeyDown event when Tab is pressed.
if (e.KeyCode == Keys.Tab) { e.IsInputKey = true; }
When in editmode thanks to Jimi
I'm sorry I thought the problem too simple. How about this. You can override ProcessCmdKey to ignore Tab when you in editmode of your DGV. Is it too brute?
I think this is simple than make a new edit control but not elegance too.
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
if (keyData == Keys.Tab && dataGridView1.EditingControl != null) { return true; }
else return base.ProcessCmdKey(ref msg, keyData);
}
from Similar problem
I want to have the Esc key undo any changes to a textbox since it got focus.
I have the text, but can't seem to figure out how to capture the Esc key. Both KeyUp and KeyPressed don't seem to get it.
This should work. How are you handling the event?
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("Escape Pressed");
}
}
Edit in reply to comment - Try overriding ProcessCmdKey instead:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape && myTextBox.Focused)
{
MessageBox.Show("Escape Pressed");
}
return base.ProcessCmdKey(ref msg, keyData);
}
is this what you're looking for?
string origStr = String.Empty;
private void txtOrig_Enter(object sender, EventArgs e)
{
origStr = txtOrig.Text;
}
private void txtOrig_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Escape))
{
txtOrig.Text = origStr;
}
}
Supposedly some keys are not considered "input keys" and so are not listened to by default. You need to handle PreviewKeyDown first to enable it.
myTextBox.PreviewKeyDown += (s, e) => {
if (e.KeyCode == Keys.Escape) {
e.IsInputKey = true;
Debug.Print("ESC should get handled now.");
}
};
However, results from testing say otherwise, so it may depend on framework version. For me, whether I do that or not, KeyDown does not get called for ESC, and whether I do that or not, KeyPress DOES get called for ESC. This is while a TextBox has focus, so it may also depend on the control.
I am implementing a search function in a windows form in c#. I have set KeyPreviewto true on the form and have added an event handler for KeyDown so I can catch things like ctrl+f, esc and enter.
I am catching these keys just fine and I'm able to make my text box appear, but I am unable to type into the box. All of the keys are going to PortsTraceForm_KeyDown(...) but they never make it to the text box. According to the msdn page about KeyPreview, setting e.Handled to false should cause the event to pass to the view in focus (the text box), but this isn't happening. I have not registered a KeyDown event for the text box, so it should be using the default behavior. Have I missed something?
KeyDown event:
private void PortsTraceForm_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
e.Handled = false;
if (e.KeyData == (Keys.F | Keys.Control)) // ctrl+f
{
e.Handled = true;
ShowSearchBar();
}
else if (e.KeyCode == Keys.Escape) // esc
{
e.Handled = true;
HideSearchBar();
}
else if (e.KeyCode == Keys.Enter) // enter
{
if (searchPanel.Visible)
{
e.Handled = true;
if (searchShouldClear)
SearchStart();
else
SearchNext();
}
}
}
show search bar:
private void ShowSearchBar()
{
FindBox.Visible = true;
FindBox.Focus(); // focus on text box
}
hide search bar:
private void HideSearchBar()
{
this.Focus(); // focus on form
FindBox.Visible = false;
}
Your TextBox likely does not have focus even though you are calling Focus(). From the documentation:
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
You can check the return value of Focus() for success, but I have had little luck in the past using that method to set focus to an arbitrary control. Instead, try using the method that the documentation suggests, i.e., call Select().
EDIT:
Nevermind (though it's still valid advice), I think I see your problem:
e.SuppressKeyPress = true
Why are you doing this? Again, from the docs:
[SuppressKeyPress] Gets or sets a value indicating whether the key event should be passed on to the underlying control
So you are intentionally preventing the TextBox from getting key events. If you want to pass the event through you shouldn't be setting that property to false.
try this example , of overrides method.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// your code here
// this is message example
MessageBox.Show(keyData.ToString());
return base.ProcessCmdKey(ref msg, keyData);
}
Regards.
DataGridView keydown event is not working when I am editing text inside a cell.
I am assigning shortcut Alt+S to save the data, it works when cell is not in edit mode, but if it is in edit mode below code is not working
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Alt | Keys.S))
{
//save data
}
}
Whenever a cell is in edit mode, its hosted control is receiving the KeyDown event instead of the parent DataGridView that contains it. That's why your keyboard shortcut is working whenever a cell is not in edit mode (even if it is selected), because your DataGridView control itself receives the KeyDown event. However, when you are in edit mode, the edit control contained by the cell is receiving the event, and nothing happens because it doesn't have your custom handler routine attached to it.
I have spent way too much time tweaking the standard DataGridView control to handle edit commits the way I want it to, and I found that the easiest way to get around this phenomenon is by subclassing the existing DataGridView control and overriding its ProcessCmdKey function. Whatever custom code that you put in here will run whenever a key is pressed on top of the DataGridView, regardless of whether or not it is in edit mode.
For example, you could do something like this:
class MyDataGridView : System.Windows.Forms.DataGridView
{
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
MessageBox.Show("Key Press Detected");
if ((keyData == (Keys.Alt | Keys.S)))
{
//Save data
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Also see related, though somewhat older, article: How to trap keystrokes in controls by using Visual C#
Another way of doing it is by using the EditingControlShowing event to redirect the event handling to a custom event handler as below:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl tb)
{
tb.KeyDown -= dataGridView1_KeyDown;
tb.KeyDown += dataGridView1_KeyDown;
}
}
//then in your keydown event handler, execute your code
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Alt | Keys.S))
{
//save data
}
}
This is true that EditingControlShowing can help, but not if you wants to catch the Enter key. In that case, one should use the following method:
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl tb = e.Control as DataGridViewTextBoxEditingControl;
tb.KeyDown -= dataGridView_KeyDown;
tb.PreviewKeyDown -= dataGridView_PreviewKeyDown;
tb.KeyDown += dataGridView_KeyDown;
tb.PreviewKeyDown += dataGridView_PreviewKeyDown;
}
}
void dataGridView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
<your logic goes here>
}
}
A simpler way I just tried out is as follows:
Set the KeyPreview property of the Form to true.
Instead of catching the KeyDown event on Grid, catch the KeyDown event on Form.
Code as follows:
Private Sub form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If grd.Focused Then
'Do your work
End If
End Sub
I worked with this
private void grdViewOrderDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
grdViewOrderDetail_KeyDown(null,null);
}
private void grdViewOrderDetail_KeyDown(object sender, KeyEventArgs e)
{
//Code
}
The solution
class MyDataGridView : System.Windows.Forms.DataGridView {
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) {
if ( keyData == Keys.Enter ) {
.
Process Enter Key
.
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Worked perfectly for me
use PreviewKeyDown event
private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
}
I am creating a small game, the game is printed onto a panel on a windows form. Now i want to capture the keydown event to see if its the arrow keys that has been pressed, the problem however is that i can't seem to capture it.
Let me explain, on the form i have 4 buttons and various other controls and if the user for instance press one of the buttons (to trigger a game event) then the button has focus and i can't capture the movements with the arrow keys.
I tried something like
private void KeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.E);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Right)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.W);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Up)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.N);
game.DrawObjects(panel1.CreateGraphics());
}
else if (e.KeyCode == Keys.Down)
{
game.MovePlayer(DonutWarsLibrary.GameObjects.Direction.S);
game.DrawObjects(panel1.CreateGraphics());
}
}
and then when the form key down event was pressed, i used this
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
KeyDown(e);
}
I also added keydown for the buttons and the various other controls on the windows form, but i am not getting any response back. I have setup a breakpoint inside the function to see if it's being called, but that breakpoint never triggers?
Any ideas?
The most optimal was to have a general KeyDown event that triggers (regardless of what control that currently has focus) and then calls the KeyDown method.
Have you set the KeyPreview property of the form to true? That will cause the form to get a "first look" at key events.
Update: getting this to work properly when a Button has focus seems to be a bit tricky. The Button control intercepts the arrow key presses and moves focus to the next or previous control in the tab order in a manner so that the KeyDown, KeyUp and KeyPress events are not raised. However, the PreviewKeyDown event is raised, so that can be used:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = ProcessKeyDown(e.KeyCode);
}
// event handler for the PreViewKeyDown event for the buttons
private void ArrowButton_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
ProcessKeyDown(e.KeyCode);
}
private bool ProcessKeyDown(Keys keyCode)
{
switch (keyCode)
{
case Keys.Up:
{
// act on up arrow
return true;
}
case Keys.Down:
{
// act on down arrow
return true;
}
case Keys.Left:
{
// act on left arrow
return true;
}
case Keys.Right:
{
// act on right arrow
return true;
}
}
return false;
}
Still, the focus moves around in a rather ugly manner...
I believe the easiest way of solving this problem is through overriding the ProcessCmdKey() method of the form. That way, your key handling logic gets executed no matter what control has focus at the time of keypress. Beside that, you even get to choose whether the focused control gets the key after you processed it (return false) or not (return true).
Your little game example could be rewritten like this:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Left)
{
MoveLeft(); DrawGame(); DoWhatever();
return true; //for the active control to see the keypress, return false
}
else if (keyData == Keys.Right)
{
MoveRight(); DrawGame(); DoWhatever();
return true; //for the active control to see the keypress, return false
}
else if (keyData == Keys.Up)
{
MoveUp(); DrawGame(); DoWhatever();
return true; //for the active control to see the keypress, return false
}
else if (keyData == Keys.Down)
{
MoveDown(); DrawGame(); DoWhatever();
return true; //for the active control to see the keypress, return false
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
Override IsInputKey behaviour
You must override the IsInputKey behavior to inform that you want the Right Arrow key to be treated as an InputKey and not as a special behavior key.
For that you must override the method for each of your controls.
I would advise you to create your won Buttons, let's say MyButton
The class below creates a custom Button that overrides the IsInputKey method so that the right arrow key is not treated as a special key. From there you can easily make it for the other arrow keys or anything else.
public partial class MyButton : Button
{
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Right)
{
return true;
}
else
{
return base.IsInputKey(keyData);
}
}
}
Afterwards, you can treat your keyDown event event in each different Button or in the form itself:
In the Buttons' KeyDown Method try to set these properties:
private void myButton1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
//DoSomething();
}
-- OR --
handle the common behaviour in the form: (do not set e.Handled = true; in the buttons)
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//DoSomething();
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
KeyPreview = true;
KeyDown += new KeyEventHandler(Form1_KeyDown);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
System.Diagnostics.Debug.Write(e.KeyCode);
}
}