How to use ScrollableControl with AutoScroll set to false

≡放荡痞女 提交于 2019-12-04 04:54:21

I ended up implementing my own custom scrolling by creating 3 child controls: an HScrollBar, a VScrollBar, and a Panel.

I hide ClientSize and ClientRectangle like so:

public new Rectangle ClientRectangle
{
    get
    {
        return new Rectangle(new Point(0, 0), ClientSize);
    }
}

public new Size ClientSize
{
    get
    {
        return new Size(
            base.ClientSize.Width - VScrollBar.Width,
            base.ClientSize.Height - HScrollBar.Height
        );
    }
}

The layout is done in OnClientSizeChanged:

protected override void OnClientSizeChanged(EventArgs e)
{
    base.OnClientSizeChanged(e);

    HScrollBar.Location = new Point(0, base.ClientSize.Height - HScrollBar.Height);
    HScrollBar.Width = base.ClientSize.Width - VScrollBar.Width;

    VScrollBar.Location = new Point(base.ClientSize.Width - VScrollBar.Width, 0);
    VScrollBar.Height = base.ClientSize.Height - HScrollBar.Height;

    cornerPanel.Size = new Size(VScrollBar.Width, HScrollBar.Height);
    cornerPanel.Location = new Point(base.ClientSize.Width - cornerPanel.Width, base.ClientSize.Height - cornerPanel.Height);
}

Each ScrollBar has their Scroll event subscribed to the following:

private void ScrollBar_Scroll(object sender, ScrollEventArgs e)
{
    OnScroll(e);
}

And finally we can allow MouseWheel events to scroll with the following:

protected override void OnMouseWheel(MouseEventArgs e)
{
    int xOldValue = VScrollBar.Value;

    if (e.Delta > 0)
    {
        VScrollBar.Value = (int)Math.Max(VScrollBar.Value - (VScrollBar.SmallChange * e.Delta), 0);
        OnScroll(new ScrollEventArgs(ScrollEventType.ThumbPosition, xOldValue, VScrollBar.Value, ScrollOrientation.VerticalScroll));
    }
    else
    {
        VScrollBar.Value = (int)Math.Min(VScrollBar.Value - (VScrollBar.SmallChange * e.Delta), VScrollBar.Maximum - (VScrollBar.LargeChange - 1));
        OnScroll(new ScrollEventArgs(ScrollEventType.ThumbPosition, xOldValue, VScrollBar.Value, ScrollOrientation.VerticalScroll));
    }
}

For custom painting, you would use the following statement:

e.Graphics.TranslateTransform(-HScrollBar.Value, -VScrollBar.Value);

This worked perfectly without the glitches present when using AutoScroll.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!