Winform Datagridview handle tab and arrow keys

僤鯓⒐⒋嵵緔 提交于 2019-12-13 13:25:05

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/15955411/winform-datagridview-handle-tab-and-arrow-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!