这是一个小小的组件,实现控制带有滚动条的控件(ListView,TreeView等)的滚动条显示。 带有滚动条的控件,通常情况下都是需要显示滚动条的时候,如果水平滚动条和垂直滚动条都需要显示,就一起显示出来。但是有的时候我们只想让其只显示一条滚动条,例如只显示垂直滚动条,我们应该怎么办呢?我们可以通过API函数:ShowScrollBar (查看)来实现。另外,我们可以通过API函数:GetWindowLong (查看)来查询当前控件是否需要显示滚动条。先定义好这两个API函数:
[DllImport("user32.dll")]
private static extern int ShowScrollBar(IntPtr hWnd, int iBar, int bShow);
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int nIndex);
现在,我们可以继承 NativeWindow 来写出我们需要的组件了。主要是重载 WndProc 函数:
protected override void WndProc(ref Message m)
{
HideScrollBar(ref m);
base.WndProc(ref m);
}
最后,来看看关键的 HideScrollBar 函数。
private void HideScrollBar(ref Message m)
{
int dwStyle = GetWindowLong(base.Handle, GWL_STYLE);
switch (_scrollBar)
{
case SB.SB_HORZ:
if ((dwStyle & WS_HSCROLL) == WS_HSCROLL)
{
ShowScrollBar(base.Handle, (int)_scrollBar, 0);
}
break;
case SB.SB_VERT:
if ((dwStyle & WS_VSCROLL) == WS_VSCROLL)
{
ShowScrollBar(base.Handle, (int)_scrollBar, 0);
}
break;
}
}