简体   繁体   中英

How to create custom shortcuts for DataGridView?

I'm trying to create a shortcut (CTRL+J) in a DataGridView control in a Windows form. The shortcut should simply do exactly what the down arrow does (ie, in most cases, change the selection to the next item).

I am trying to handle CTRL+J by overriding the form's FormKeyDown event and using SendKeys.SendWait("{DOWN}") if FormKeyDown receives the J key and Ctrl as a modifier.

However, when I send the {DOWN} key, it acts like Ctrl+Down since the user is still holding the CTRL key!

How can I create the custom shortcut so that it has exactly the same behavior as a shortcut the DataGridView already supports?

You should avoid relying on mimicking user input with SendKeys and instead use the correct API for programmatic selection available on DataGridView class. You can check the programmatic selection section on the following page:

Selection Modes in the Windows Forms DataGridView Control

When implementing the code for programmatic selection you need to take in consideration the SelectionMode configured for your data grid view.


Alternatively you can subclass from DataGridView and implement your custom shortcuts so that they redirect to the existing ones. Example:

public class MyDataGridView : DataGridView
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.J))
        {
            this.ProcessDownKey(Keys.Down);

            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

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