Oct 7, 2010

Draw line on Windows Form

Drawing simple lines on a Windows form is not easier as there is no Line control. Still you can make a line by using a Panel control and setting its width or height to a few pixels. But if you want a real line, the secret is in understanding the correct set of library methods you need.

To draw a line with code you need to use GDI +(i.e. the .NET graphics library)

In VB:




Private Sub btnOk_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint 
    Dim g As Graphics = e.Graphics 
    Dim penLine As Pen = New Pen(Color.CornflowerBlue, 12) 
    g.DrawLine(penLine, 15, 0, 15, Me.Height) 
    penLine.Dispose() 
End Sub


In C#:



private void btnOk_Paint(object sender,System.Windows.Forms.PaintEventArgs e) 
{ 
  Graphics g = e.Graphics; 
  Pen penLine = new Pen(Color.CornflowerBlue, 12); 
  g.DrawLine(penLine, 15, 0, 15, this.Height); 
  penLine.Dispose(); 
} 

No comments:

Post a Comment