winform DataGridView重绘滚动条样式
时间: 2023-07-20 16:38:24 浏览: 158
winform 滚动条示例
4星 · 用户满意度95%
要重绘WinForm DataGridView的滚动条样式,需要继承DataGridView并重写它的WndProc方法。以下是一个示例代码,可以实现自定义滚动条样式:
```csharp
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class CustomDataGridView : DataGridView
{
private const int WM_PAINT = 0xF;
private const int WM_NCPAINT = 0x85;
private const int WM_NCCALCSIZE = 0x83;
private const int WM_ERASEBKGND = 0x14;
private bool isScrolling = false;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_PAINT:
base.WndProc(ref m);
DrawScrollBar();
break;
case WM_NCPAINT:
case WM_NCCALCSIZE:
case WM_ERASEBKGND:
break;
default:
base.WndProc(ref m);
break;
}
}
private void DrawScrollBar()
{
if (!isScrolling)
{
// 获取滚动条的Graphics对象
Graphics g = this.CreateGraphics();
// 绘制滚动条背景
Rectangle bgRect = new Rectangle(this.VerticalScrollingOffset + this.Width - SystemInformation.VerticalScrollBarWidth, this.ColumnHeadersHeight, SystemInformation.VerticalScrollBarWidth, this.Height - this.ColumnHeadersHeight);
g.FillRectangle(new SolidBrush(this.BackgroundColor), bgRect);
// 绘制滚动条轨道
Rectangle trackRect = new Rectangle(bgRect.X + 1, bgRect.Y + SystemInformation.VerticalScrollBarArrowHeight, bgRect.Width - 2, bgRect.Height - 2 * SystemInformation.VerticalScrollBarArrowHeight);
ControlPaint.DrawScrollTrack(g, trackRect, ScrollOrientation.Vertical);
// 绘制滚动条滑块
Rectangle thumbRect = new Rectangle(bgRect.X + 1, bgRect.Y + SystemInformation.VerticalScrollBarArrowHeight + (this.FirstDisplayedScrollingRowIndex * trackRect.Height / this.RowCount), bgRect.Width - 2, this.DisplayedRowCount(false) * trackRect.Height / this.RowCount);
ControlPaint.DrawScrollThumb(g, thumbRect, ScrollState.Focused);
// 释放Graphics对象
g.Dispose();
}
}
protected override void OnScroll(ScrollEventArgs e)
{
isScrolling = true;
base.OnScroll(e);
isScrolling = false;
this.Invalidate(new Rectangle(this.Width - SystemInformation.VerticalScrollBarWidth, this.ColumnHeadersHeight, SystemInformation.VerticalScrollBarWidth, this.Height - this.ColumnHeadersHeight()));
}
}
```
在上述代码中,我们首先重写了DataGridView的WndProc方法,在其中处理WM_PAINT消息并调用DrawScrollBar方法绘制滚动条。DrawScrollBar方法中,我们使用CreateGraphics方法获取滚动条的Graphics对象,然后绘制滚动条背景、轨道和滑块。最后,记得在OnScroll方法中调用Invalidate方法重新绘制滚动条。
使用上述代码,我们可以实现自定义滚动条样式。需要注意的是,由于我们使用了CreateGraphics方法获取Graphics对象,因此需要在绘制完滚动条后释放该对象。此外,在绘制滑块时,我们使用了FirstDisplayedScrollingRowIndex和DisplayedRowCount方法来获取当前滚动条位置和可见行数,因此需要确保这些属性已经被正确设置。
阅读全文