Lecture 8-1 C# With SQL 3ed Class
Lecture 8-1 C# With SQL 3ed Class
Windows Forms uses the C# programming language. Its built-in classes and
methods allow you to draw various shapes onto a Windows Form canvas. These
include the Graphics, Pen, Color, and Brush classes.
Class Description
The Graphics class allows you to draw shapes and lines onto
the canvas. It includes methods such as:
Graphics • DrawLine(Pen, Point1, Point2)
• DrawRectangle(x, y, width, height)
• DrawPolygon(Pen, PointF[])
The Pen class allows you to specify the properties of a 'pen' tip
which you can use to draw your shapes. You can specify
Pen properties such as color, thickness, or dash style. Methods
include:
• SetLineCap(LineCap, LineCap, DashCap)
You can create objects based on these shapes, and use them
Rectangle, Line, wen calling methods such as DrawRectangle(). Instead of
Polygon, Ellipse passing the x, y, width, and height as arguments, you can
choose to pass an existing Rectangle object instead.
How to Add a Paint on Form Load Event Handler
First, add an event handler to draw shapes when the canvas loads.
You can use a Color, Pen, and the DrawLine() method to draw lines on a canvas.
1. Inside the Form1_Paint() function, create a Color object with the color you
want the line to be. Then, create a Pen object to draw the line with.
2. The DrawLine() method from the Graphics class will draw a line using the
pen. This will start drawing a line from an x, y position to another x, y
position.
3. You can modify the properties for the pen object to change its width, dash
style, and start or end cap.
blackPen.Width = 20;
blackPen.DashStyle = System. Drawing. Drawing2D.DashStyle. Dash;
blackPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
4. Press the green play button at the top of Visual Studio to see the changes.
You can use the shapes classes for different shapes, or draw shapes manually onto
the canvas.
1. Create a Color and Pen object as shown in the previous steps. Then, use the
DrawRectangle() method to create the rectangle. The arguments are the x
and y coordinates for the top-left of the rectangle, along with its width and
height.
2. You can also create a rectangle using the Rectangle Class. First, create a
Rectangle object. The arguments are also the x and y coordinates for the top-
left corner, width, and height.
e.Graphics.DrawRectangle(redPen, rectangle);
4. Press the green play button at the top of Visual Studio to see the changes.
5. Go back to the code to draw other shapes. Use the DrawEllipse() function to
draw a circle.
When you draw a circle, the x and y coordinates (x=400, y=150) refer to the
top-left corner of the circle, not the center of the circle.
e.Graphics.DrawPolygon(bluePen, coordinatesForTriangle);
The DrawPolygon() method will draw lines between the points specified.
4. Use the HatchBrush to fill the shape using a different fill style, such as a
horizontal or vertical pattern.