DataGridView CellMouseEnter检测灰色区域

时间:2018-08-03 15:33:42

标签: c# winforms user-interface datagridview cursor

我正在尝试在DataGridView控件中模拟一个悬停事件,以在Cursor.Hand悬停时显示一个DataGridViewImageColumn

我正在尝试此操作(订阅CellMouseEnter

dgv_tabla.CellMouseEnter += dgv_tabla_Hover;

然后检查RowIndex是否为-1

private void dgv_tabla_Hover(object sender, DataGridViewCellEventArgs e)
{
    //The index of the column where i want to show Cursor.Hand
    var index = dgv_tabla.Columns["Remove"].Index;

    if (e.ColumnIndex == index && e.RowIndex >= 0)
        dgv_tabla.Cursor = Cursors.Hand;
    else
        dgv_tabla.Cursor = Cursors.Default;
}

问题是,当我将鼠标悬停在“删除”单元格上并向下移动鼠标(到“灰色区域”)时,Cursor.Hand不会变为Cursor.Default

可以更好地理解图像: enter image description here

有什么办法可以做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:1)

使用CellMouseLeave事件将光标重置为默认值。在这种情况下,您不需要else分支:

dgv_tabla.CellMouseEnter += dgv_tabla_Hover;
dgv_tabla.CellMouseLeave += dgv_tabla_CellMouseLeave;

private void dgv_tabla_Hover(object sender, DataGridViewCellEventArgs e)
{
    //The index of the column where i want to show Cursor.Hand
    var index = dgv_tabla.Columns["Remove"].Index;

    if (e.ColumnIndex == index && e.RowIndex >= 0)
        dgv_tabla.Cursor = Cursors.Hand;
}

private void dgv_tabla_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    dgv_tabla.Cursor = Cursors.Default;
}

答案 1 :(得分:1)

另一种解决方案是使用MouseMove事件并在上面的注释中进行HitTest as suggested by TaW。在这种情况下,您的代码将如下所示:

dgv_tabla.MouseMove += Dgv_tabla_MouseMove;


private void Dgv_tabla_MouseMove(object sender, MouseEventArgs e)
{
    int index = dgv_tabla.Columns["Remove"].Index;

    DataGridView.HitTestInfo info = dgv_tabla.HitTest(e.X, e.Y);
    if (info.ColumnIndex == index && info.RowIndex >= 0)
        dgv_tabla.Cursor = Cursors.Hand;
    else
        dgv_tabla.Cursor = Cursors.Default;
}