阻止datagridview对象被点击和窃取焦点的最好方法

本文关键字:焦点 方法 对象 datagridview 阻止 | 更新日期: 2023-09-27 18:13:57

我的表单上有两个datagridview。我有一个(dgv1),我编辑的数据和一个(dgv2),仅用于查看(捕捉点击动作)。例如,我可能在dgv1中编辑一个单元格(文本),需要双击dgv2中的一行,将内容放入dgv1(类似于快速复制/粘贴)。目前,我必须在dgv2上使用鼠标右键双击事件,因为如果在任何时候我左键单击或左键双击焦点将从dgv1移动到dgv2,并停止编辑我正在工作的dgv1单元格。

我想看看是否有可能能够做到我正在做什么通过双击鼠标左键点击dgv2 ?

我唯一能想到的是尝试找到一种方法来禁用鼠标左键单击事件,但我希望基本上只是让它"不响应",就像当你双击右键在单元格/行。

想法?

编辑:dgv2 CellMouseDoubleClick事件示例

private void dgv2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button != MouseButtons.Right) return;
    DataGridView dgvSrc = (DataGridView)sender;
    DataGridView dgvDest = dgv1;
    DataGridViewCell cellSrc = dgvSrc.Rows[e.RowIndex].Cells["dgv2VariableName"];
    foreach (DataGridViewCell cell in dgvDest.SelectedCells)
    {
        if (cell.IsInEditMode && dgvDest.CurrentCell.EditType == typeof(DataGridViewTextBoxEditingControl))
        {
            //Target inserting the variable in the current selected edited area inside the textbox
            TextBox editBox = (TextBox)dgvDest.EditingControl;
            int selStartPos = editBox.SelectionStart;
            int selEndPos = selStartPos + editBox.SelectionLength;
            editBox.Text = editBox.Text.Substring(0, selStartPos) + cellSrc.Value.ToString() + editBox.Text.Substring(selEndPos);
            editBox.SelectionStart = selStartPos + cellSrc.Value.ToString().Length;
        }
        else
        {
            //Just override the entire cell
            cell.Value = cellSrc.Value;
        }
    }
}

阻止datagridview对象被点击和窃取焦点的最好方法

您可以将DataGridView设置为不可选择的,也可以将其设置为只读的。然后,当用户双击它的单元格时,它不会从已聚焦控件中窃取焦点。

要使其为只读,只需将其ReadOnly属性设置为true。要使其为非可选的,可以从DataGridView中派生,并在构造函数中,使其为非可选的:

SetStyle(ControlStyles.Selectable, false);

注意

因为SetStyle是受保护的,你不能在你的控制之外使用它。但是你可以用反射来调用它。因为它是一个有用的方法,所以您可以创建一个扩展方法,就像我在这里使用的那样来模拟屏幕上的键盘。然后你可以用它来对付所有的控件。以下是我对第二个DataGridView的设置:

this.dataGridView2.SetStyle(ControlStyles.Selectable, false);
this.dataGridView2.ReadOnly = true;

下面是我用来暴露SetStyle的扩展方法:

public static class Extensions
{
    public static void SetStyle(this Control control, ControlStyles flags, bool value)
    {
        Type type = control.GetType();
        BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
        MethodInfo method = type.GetMethod("SetStyle", bindingFlags);
        if (method != null)
        {
            object[] param = { flags, value };
            method.Invoke(control, param);
        }
    }
}