winform DataGridView重绘滚动条
时间: 2023-07-20 16:05:08 浏览: 215
winform_DataGridView常见属性.docx
对于winform中的DataGridView控件,重绘滚动条的方式如下:
1. 创建一个新的滚动条,使用CreateWindow函数,指定ScrollBar类和style为WS_CHILD | WS_VISIBLE | SBS_VERT | SBS_RIGHTALIGN。
2. 让新创建的滚动条关联到DataGridView的滚动条事件,使用SetScrollInfo函数设置滚动条信息,包括滚动条范围,当前位置和页大小等等。
3. 在DataGridView的Paint事件中重绘控件,包括滚动条和数据区域。
代码示例:
```
private const uint WM_HSCROLL = 0x0114;
private const uint WM_VSCROLL = 0x0115;
private const uint SB_THUMBTRACK = 5;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
IntPtr hScrollBar;
private void dataGridView1_Resize(object sender, EventArgs e)
{
int borderWidth = SystemInformation.Border3DSize.Width;
int x = dataGridView1.Width - SystemInformation.VerticalScrollBarWidth - borderWidth;
int y = dataGridView1.Top + borderWidth;
int width = SystemInformation.VerticalScrollBarWidth;
int height = dataGridView1.Height - 2 * borderWidth;
if (hScrollBar == IntPtr.Zero)
{
hScrollBar = CreateWindow("SCROLLBAR", null, WS_CHILD | WS_VISIBLE | SBS_VERT | SBS_RIGHTALIGN, x, y, width, height, dataGridView1.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
SetScrollInfo(hScrollBar, SIF_ALL, 0, 100, 10, 0);
}
else
{
MoveWindow(hScrollBar, x, y, width, height, true);
}
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
IntPtr wParam;
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
wParam = (IntPtr)(SB_THUMBTRACK << 16) | (IntPtr)(e.NewValue & 0xFFFF);
SendMessage(dataGridView1.Handle, WM_HSCROLL, wParam, IntPtr.Zero);
}
else if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
{
wParam = (IntPtr)(SB_THUMBTRACK << 16) | (IntPtr)(e.NewValue & 0xFFFF);
SendMessage(hScrollBar, WM_VSCROLL, wParam, IntPtr.Zero);
}
dataGridView1.Invalidate();
}
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.White, dataGridView1.ClientRectangle);
IntPtr hDC = e.Graphics.GetHdc();
SendMessage(dataGridView1.Handle, WM_PRINTCLIENT, hDC, PRF_CLIENT);
e.Graphics.ReleaseHdc(hDC);
if (hScrollBar != IntPtr.Zero)
{
hDC = e.Graphics.GetHdc();
SendMessage(hScrollBar, WM_PRINTCLIENT, hDC, PRF_CLIENT);
e.Graphics.ReleaseHdc(hDC);
}
}
```
阅读全文