如果形状的高度大于窗体的高度,则显示滚动条

时间:2019-11-19 10:13:19

标签: c# graphics scrollbar shapes paintevent

如果我的形状高度大于表单高度,我只需要在表单上显示滚动条。这样,当用户向下滚动时,它可以显示形状的末端。

这是我的代码:

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 个答案:

答案 0 :(得分:3)

您需要启用表单的AutoScroll属性,在工程图中使用AutoScrollPosition坐标,并设置AutoScrollMinSize属性以包含您的形状:

在构造函数中添加:

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

和绘画例程:

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);
    }
}

祝你好运。