【问题标题】:How to detect if cursor is hovering over text inside DataGridViewCell如何检测光标是否悬停在 DataGridViewCell 内的文本上
【发布时间】:2021-06-12 23:02:29
【问题描述】:

我想在我的 DataGridView 中显示一些自定义工具提示,具体取决于光标是否悬停在单元格的文本上。

这样做的原因是因为有时单元格中的文本很少,并且仅在 MouseEnter 事件上显示工具提示基本上会使得每当用户的光标位于网格上的任何位置时都会有一个工具提示。这会很烦人。

有没有办法检测用户的光标是否真的在文本本身上?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    以下逻辑应该起作用:

    private bool IsCursorOverCellText(DataGridView dgv, int columnIndex, int rowIndex)
    {
        if (dgv[columnIndex, rowIndex] is DataGridViewCell cell)
        {
            var cursorPosition = dgv.PointToClient(Cursor.Position);
            var cellAreaWithTextInIt =
                new Rectangle(dgv.GetCellDisplayRectangle(columnIndex, rowIndex, true).Location, cell.GetContentBounds(rowIndex).Size);
    
            return cellAreaWithTextInIt.Contains(cursorPosition);
        }
    
        return false;
    }
    
    private void DataGridView_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.ColumnIndex < 0 || e.RowIndex < 0)
            return;
    
        if (sender is DataGridView dgv)
        {
            if (IsCursorOverCellText(dgv, e.ColumnIndex, e.RowIndex))
                dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red; 
            else
                dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
        }
    }
    

    这是一个演示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多