简体   繁体   中英

Capturing Ctrl+A shortcut key

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.

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 )

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);
    }
}

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");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM