Reputation: 1534
I need to capture a kepress combo on the keyboard so i can override the standard function, i've tried the following:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
MessageBox.Show("Hello");
}
}
But when pressing Ctrl+A
the message is not triggered. The end aim is to override the windows shortcut 'select all' in a DataGridView
within the Form1
to ensure only certain rows are selected when Ctrl+A
is pressed in the form window.
Upvotes: 1
Views: 1023
Reputation: 11
Just for the records: This can be done with KeyPress
too, because the Ctrl+Letter keys are "special":
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar=='\u0001') //Ctrl+A, B=2, C=3 ...
{
MessageBox.Show("Control + A");
}
}
Upvotes: 0
Reputation: 125187
In general to handle a shortcut key, you can override ProcessCmdKey
. By overriding this method, you can handle the key combination:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.A))
{
MessageBox.Show("Control + A");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Returning true
, means it's handled by your code and the key will not pass to the child control. So it's enough to override this method at form level.
But if you are talking specifically about DataGridView
to customize the Ctrl + A
combination, you can override ProcessDataGridViewKey
method of the DataGridView
:
public class MyDataGridView : DataGridView
{
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyData == (Keys.A | Keys.Control))
{
MessageBox.Show("Handled");
return true;
}
return base.ProcessDataGridViewKey(e);
}
}
Upvotes: 0
Reputation: 186668
First, ensure that Form1
property
KeyPreview = true
Next, do not forget to handle the message (you don't want DataGridView
process the message and do SelectAll
)
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
e.Handled = true; // <- do not pass the event to DataGridView
MessageBox.Show("Hello");
}
}
So you preview KeyDown
on the Form1
(KeyPreview = true
), perform the required action, and prevent DataGridView
from executing select all (e.Handled = true
)
Upvotes: 2