当鼠标悬停在一行上时,突出显示DataGridView中的行

bla*_*elt 3 c# datagridview mouseover winforms

我有一个DataGridView,当前它看起来像下面的图像:

在此处输入图片说明

我要达到的目的是,当我将鼠标悬停在任何行的任何列上时,应突出显示整行,并且背景颜色应变为不同的颜色,如下图所示。

在此处输入图片说明

您能帮我解决这个问题吗?

Rez*_*aei 6

您可以突出显示RowPostPaint事件中鼠标指针下方的行,也可以覆盖OnRowPostPaint派生方法中的方法DataGridView。在这种方法中,您可以自己绘制整个行,也可以仅绘制其中的一部分或在行上绘制一些内容:

在此处输入图片说明

例

using System;
using System.Drawing;
using System.Windows.Forms;
public class MyDataGridView : DataGridView
{
    public MyDataGridView() { DoubleBuffered = true; }
    protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
    {
        base.OnRowPostPaint(e);
        if (this.RectangleToScreen(e.RowBounds).Contains(MousePosition))
        {
            using (var b = new SolidBrush(Color.FromArgb(50, Color.Blue)))
            using (var p = new Pen(Color.Blue))
            {
                var r = e.RowBounds; r.Width -= 1; r.Height -= 1;
                e.Graphics.FillRectangle(b, r);
                e.Graphics.DrawRectangle(p, r);
            }
        }
    }
    protected override void OnMouseMove(MouseEventArgs e){
        base.OnMouseMove(e); this.Invalidate();
    }
    protected override void OnMouseEnter(EventArgs e){
        base.OnMouseEnter(e); this.Invalidate();
    }
    protected override void OnMouseLeave(EventArgs e){
        base.OnMouseLeave(e); this.Invalidate();
    }
    protected override void OnScroll(ScrollEventArgs e){
        base.OnScroll(e); this.Invalidate();
    }
}
Run Code Online (Sandbox Code Playgroud)