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.

1 comment:

  1. Science assignments can cover a wide range of subjects, from experiments and scientific theories to calculations and research-based questions. Students who need help with science assignment tasks can benefit from clear academic guidance and structured explanations. Breaking complicated concepts into smaller sections makes learning much easier. Proper support can also help students understand scientific methods, organize their findings, and improve their overall confidence when completing challenging coursework and preparing for assessments.

    ReplyDelete

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...