C# show scrollbars if shape height is greater than form height

廉价感情. 提交于 2019-12-02 22:07:52

问题


I just need to show scrollbars on forms if my shape height is greater than the form height. That way, when the user scrolls down, it can show the end of the shape.

This is my code:

public partial class Form1: Form {
    public Form1() {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {
    }

    private void Form1_Paint(object sender, PaintEventArgs e) {
        e.Graphics.DrawLine(new Pen(Color.Black, 2), 100, 50, 100, 1000);
        //if line height > form height then show scroll bars
    }
}

回答1:


You need to enable the AutoScroll property of the form, use the AutoScrollPosition coordinates in drawings, and set the AutoScrollMinSize property to contain your shapes:

In the constructor add:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        AutoScroll = true;
    }
}

and the painting routine:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    using (Matrix m = new Matrix(1, 0, 0, 1, AutoScrollPosition.X, AutoScrollPosition.Y))
    {
        var sY = VerticalScroll.Value;
        var sH = ClientRectangle.Y;
        var w = ClientRectangle.Width - 2 - (VerticalScroll.Visible ? SystemInformation.VerticalScrollBarWidth : 0);
        var h = ClientRectangle.Height;                
        var paintRect = new Rectangle(0, sY, w, h); //This will be your painting rectangle.
        var g = e.Graphics;

        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.Transform = m;
        g.Clear(BackColor);

        using (Pen pn = new Pen(Color.Black, 2))
            e.Graphics.DrawLine(pn, 100, 50, 100, 1000);

        sH += 1050; //Your line.y + line.height
        //Likewise, you can increase the w to show the HorizontalScroll if you need that.
        AutoScrollMinSize = new Size(w, sH);
    }
}

Good Luck.



来源:https://stackoverflow.com/questions/58931515/c-sharp-show-scrollbars-if-shape-height-is-greater-than-form-height

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