How to make a diagonal line divide two panels in C# WinForms?

If you want to divide the left and the right parts of the form evenly with the diagonal line in the middle, you can refer to the following code:

private void panel3_Paint(object sender, PaintEventArgs e)
{
    base.OnPaint(e);
    using (Graphics g = e.Graphics)
    {
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        var p = new Pen(Color.Red, 3);
        var point1 = new Point(0, 0);
        var point2 = new Point(panel3.Width, panel3.Height);
        g.DrawLine(p, point1, point2);
    }
}

You can change the color and size of the diagonal line in the code.

enter image description here


I would put this into an own user control. Afterwards you could set everything through ForeColor, BackgroundColor, Thickness and RightToLeft:

public class DiagonalSeparator : UserControl
{
    private int thickness = 3;

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Graphics g = e.Graphics)
        {
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            var p = new Pen(ForeColor, thickness);
            var point1 = RightToLeft == RightToLeft.No ? new Point(0, 0) : new Point(Width, 0);
            var point2 = RightToLeft == RightToLeft.No ? new Point(Width, Height) : new Point(0, Height);
            g.DrawLine(p, point1, point2);
        }
    }

    [DefaultValue(3)]
    [Description("The thickness of the drawn line"), Category("Appearance")]
    [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public int Thickness
    {
        get
        {
            return thickness;
        }

        set
        {
            thickness = value;
            Invalidate();
        }
    }
}

This control can then be used as any other control within the designer and you can check if the visualization works as expected.