Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a line in a WinForms Application?

I want to create a simple 3D line in a WinForms application to improve visual arrangement of my form layout. This line is exacly like the line in About Windows dialog (can be opened in Windows Explorer -> Help -> About Windows).

An example be checked here. The last line (3D) is the one I want, not the first one.

How can this be done in C# or Visual Basic (.NET)?

like image 885
RHaguiuda Avatar asked Jun 21 '10 18:06

RHaguiuda


People also ask

How do I draw a line in Visual Studio Form?

To draw a line on a form, you do the following: Set up a Graphics object with CreateGraphics() Set up a Pen object, and specify a colour and line width. Use the DrawLine Subroutine or method using your Pen, and some position coordinates.


2 Answers

Add a Label control with a 3D border and with no text then set the height to 2.

like image 92
noelicus Avatar answered Oct 04 '22 11:10

noelicus


If you use SysInternals' ZoomIt utility, you can see that this is simply two lines. A dark gray one above a white one. Drawing lines is simple enough with Graphics.DrawLine(), you just need to make sure you pick a dark color that work well with the form's BackColor. That isn't always battleship gray if the user selected another theme. Which makes the GroupBox trick fall flat.

This sample code is serviceable:

    protected override void OnPaint(PaintEventArgs e) {
        Color back = this.BackColor;
        Color dark = Color.FromArgb(back.R >> 1, back.G >> 1, back.B >> 1);
        int y = button1.Bottom + 20;
        using (var pen = new Pen(dark)) {
            e.Graphics.DrawLine(pen, 30, y, this.ClientSize.Width - 30, y);
        }
        e.Graphics.DrawLine(Pens.White, 30, y+1, this.ClientSize.Width - 30, y+1);
    }

Note the use of button1 in this code, there to make sure the line is drawn at the right height, even when the form is rescaled. Pick your own control as a reference for the line.

like image 37
Hans Passant Avatar answered Oct 04 '22 11:10

Hans Passant