键盘上的多重选择,用于datagridview c#

时间:2015-10-12 10:08:22

标签: c# .net datagridview keyboard-shortcuts multipleselection

我需要为datagridview创建一些键盘快捷键。 我需要允许用户在不使用鼠标的情况下选择多个行。在Windows资源管理器中例如,您可以: 按住Ctrl (先选择) Up/down (转到下一个选择) Space (选择其他人)。 这可以在C#吗?

1 个答案:

答案 0 :(得分:2)

是的,这是可能的。因为 Ctrl + 已经有默认行为(例如导航)分别在最左侧,最右侧,最顶层和最底层的单元格中,您必须从DataGridView类继承并覆盖ProcessDataGridViewKey方法来处理这些用户操作以及 Ctrl + Space 用于选择行。

public class MultSelectKeyDGV : DataGridView
{
    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        KeyEventArgs keyEventArgs = null;
        DataGridViewSelectedCellCollection selectedCells = null;
        bool selectRow = false;

        if (e.Control)
        {
            switch (e.KeyCode)
            {
                case Keys.Down:
                    keyEventArgs = new KeyEventArgs(Keys.Down);
                    selectedCells = this.SelectedCells;
                    break;
                case Keys.Up:
                    keyEventArgs = new KeyEventArgs(Keys.Up);
                    selectedCells = this.SelectedCells;
                    break;
                case Keys.Right:
                    keyEventArgs = new KeyEventArgs(Keys.Right);
                    selectedCells = this.SelectedCells;
                    break;
                case Keys.Left:
                    keyEventArgs = new KeyEventArgs(Keys.Left);
                    selectedCells = this.SelectedCells;
                    break;
                case Keys.Space:
                    keyEventArgs = new KeyEventArgs(Keys.None);
                    selectRow = true;
                    break;
                default:
                    keyEventArgs = e;
                    break;
            }
        }
        else
        {
            keyEventArgs = e;
        }

        bool result = base.ProcessDataGridViewKey(keyEventArgs);

        if (e.Control)
        {
            this.CurrentRow.Selected = selectRow;
            this.KeepSelected(selectedCells); 
        }

        return result;
    }

    private void KeepSelected(DataGridViewSelectedCellCollection selected)
    {
        if (selected != null && this.MultiSelect)
        {
            foreach (DataGridViewCell cell in selected)
            {
                cell.Selected = true;
            }
        }
    }
}

现在只需使用此类的实例替换DataGridViewForm对象的实例即可。

Screen-shot of Keyboard selecting rows