C# – Winform Datagridview handle tab and arrow keys

cdatagridviewkeydownwinforms

I want to handle the KeyDown event on the DataGridView cell. I use the following code to get the KeyDown event on cell:

private void dgvData_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            var tb = (DataGridViewTextBoxEditingControl)e.Control;

            tb.KeyDown += cell_KeyDown;
        }

But looks like I cannot handle some special keys like tab and arrows. Those keys does not go to my cell_KeyDown method. So I try to handle them in the DataGridView's KeyDown event:

private void dgvData_KeyDown(object sender, KeyEventArgs e)
{
// handle keys
}

In that event, I still cannot capture the Tab key. I can capture the arrow keys, however, after handling my custom events, it still goes to other cells by the arrow. I want to stay in the cell.

Then I extend the DataGridView like this:

class DataGridViewSp : DataGridView
    {

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Tab)
            {
                //todo special handling
                return true;
            }

            else if (keyData == Keys.Down)
            {
                //todo special handling
                return true;
            }

            else if (keyData == Keys.Up)
            {
                //todo special handling
                return true;
            }
            else
            {
                return base.ProcessDialogKey(keyData);
            }
        }
    }

Now I can capture the Tab key in this overridden ProcessDialogKey method. But Still, it does not capture the Down and Up arrow keys. Is there anything wrong?

The perfect solution would be when in cell editing mode, it handles tab and arrow keys in my way and stay in the cell. When in the grid, arrow and tab keys work in a normal way.

Best Answer

Instead of ProcessDialogKey use ProcessCmdKey. Then you will capture all the keys you need.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    if (keyData == Keys.Tab)
    {
        //todo special handling
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
Related Topic