具有和不具有数据的 DataGridView 中的按键修饰符

Keypress modifiers in a DataGridView with and without data

我正在尝试在派生自 DataGridView 的用户控件中实现 CTRL+C 复制操作。

我要Ctrl+C复制datagridview中选中的单元格,Ctrl+Shift+C复制选中的单元格单元格列header文本.

我设置了两个复制例程,它们工作正常。我遇到的问题是分配 key_down 处理程序。

这是我的 keyDown 代码:

 protected virtual void DataGridViewEx_KeyDown(object sender, KeyEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("-------------------------------");
        System.Diagnostics.Debug.WriteLine("KeyCode = " + e.KeyCode.ToString());
        System.Diagnostics.Debug.WriteLine("KeyValue = " + e.KeyValue.ToString());
        System.Diagnostics.Debug.WriteLine("KeyData = " + e.KeyData.ToString());
        System.Diagnostics.Debug.WriteLine("Modifiers = " + e.Modifiers.ToString());
        System.Diagnostics.Debug.WriteLine("-------------------------------");


        if ((e.Control & e.Shift) && e.KeyCode == Keys.C)
        {
            System.Diagnostics.Debug.WriteLine("CTRL+SHIFT+C Pressed");
            CopyToClipboard(CopyMode.SelectedCellsWithHeaders);
            e.Handled = true;
        }
        if (e.Control && e.KeyCode == Keys.C)
        {
            System.Diagnostics.Debug.WriteLine("CTRL+C Pressed");
            CopyToClipboard(CopyMode.SelectedCellsOnly);
            e.Handled = true;
        }

        else if (e.Control && e.KeyCode == Keys.V)
        {
            PasteClipboard();
            e.Handled = true;
        }
    }

现在:这是我不明白的地方: 当我在空网格(即没有数据、列等)上尝试此操作时,我得到以下信息:

Ctrl+C:

KeyCode = C KeyValue = 67 KeyData = C, Shift, Control Modifiers = Shift, Control

Ctrl+Shift+C

KeyCode = C KeyValue = 67 KeyData = C, Shift, Control Modifiers = Shift, Control

但是:一旦我将数据粘贴到网格中,完全相同的按键操作会产生以下结果:

Ctrl+C

KeyCode = C KeyValue = 67 KeyData = C, Control Modifiers = Control

Ctrl+Shift+C

KeyCode = ShiftKey KeyValue = 16 KeyData = ShiftKey, Shift, Control Modifiers = Shift, Control

当网格中有数据时,"C" 按键不再被识别,我只能按 Ctrl+Shift。

单元格未处于编辑模式(您可以看到 Ctrl+C 可以正常工作)。我可以将其更改为类似 Ctrl+K 的内容,但我想了解这里可能发生的情况。有什么想法吗?

键修饰符在 KeyDown 事件处理程序中有一些特殊行为。为了处理您特殊复制需求的修饰符检查,我建议遵循 the 3rd part of my solution here,并进行修改。即,创建一个 class 继承自 DataGridView:

public class CopyDataGridView : DataGridView
{
    public bool ProcessShiftCopy { get; set; }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        ProcessShiftCopy = keyData == (Keys.Control | Keys.Shift | Keys.C);
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

然后按照以下步骤操作:

  1. CopyDataGridView 的实例替换您的 DataGridView
  2. 处理 CopyDataGridView.KeyUp 事件而不是 DataGridView.KeyDown。这是因为 KeyDown 不会按照我们想要的方式触发键修饰符,但 KeyUp 会。
  3. 替换:

    if ((e.Control & e.Shift) && e.KeyCode == Keys.C)
    

    与:

    if (yourCopyDataGridView.ProcessShiftCopy)
    

    处理Ctrl+Shift+C.