Sunday 21 May 2023

Program to Draw a Line in C#

 Certainly! Here's an example program in C# that uses the `System.Drawing` namespace to draw a line on a Windows Form:


Mohit Kumar Tyagi

using System;

using System.Drawing;

using System.Windows.Forms;


public class LineDrawingForm : Form

{

    public LineDrawingForm()

    {

        // Set the form size and title

        Size = new Size(400, 400);

        Text = "Line Drawing Example";

    }


    protected override void OnPaint(PaintEventArgs e)

    {

        base.OnPaint(e);


        // Create a Graphics object from the Form's CreateGraphics() method

        Graphics g = e.Graphics;


        // Set the line color and thickness

        Pen pen = new Pen(Color.Black, 2);


        // Draw the line from point (50, 50) to point (300, 300)

        g.DrawLine(pen, 50, 50, 300, 300);


        // Dispose of the pen and graphics objects

        pen.Dispose();

        g.Dispose();

    }


    public static void Main()

    {

        // Create an instance of the LineDrawingForm class

        Application.Run(new LineDrawingForm());

    }

}



To run this program, create a new Windows Forms Application project in Visual Studio or any other C# IDE, and replace the default code with the code above. When you run the program, it will display a window with a line drawn from point (50, 50) to point (300, 300).


Note that this example uses the `OnPaint` method to handle the drawing of the line. It's called automatically when the form needs to be painted. The `Pen` class is used to define the color and thickness of the line, and the `DrawLine` method of the `Graphics` class is used to actually draw the line.

No comments:

Post a Comment

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form: // Mohit Kumar Tyagi using...