Download C# Programming: Creating 'Hello World' Applications with Console and Window and more Slides C programming in PDF only on Docsity!
CS 112 Introduction to
Programming
Lecture #24:
Window Applications; Graphics
Programming; GUI
http://flint.cs.yale.edu/cs112/
C# Console Application
r Program specifications (optional)
// File: HelloWorld.cs CS112 Demo
// Classes: HelloWorld
// This program prints the string "Hello World!”
r Library imports (optional)
using System;
r Class and namespace definitions
class HelloWorld
static void Main(string[] args)
Console.WriteLine(“Hello World!”);
Really Simple C# Window Application
r Program specifications (optional)
// File: HelloWorld.cs CS112 Demo // // Author: Zhong Shao Email: [email protected] // // Classes: HelloWorld // -------------------- // This program shows a message box. // //==========================================================
r Library imports (optional)
using System; using System.Windows.Forms;
r Class and namespace definitions
class HelloWorld
static void Main(string[] args)
MessageBox.Show(“Hello World!”);
Console Application vs. Window
Application
r Console Application
m No visual component
m Only text input and output
m Run under Command Prompt or DOS Prompt
r Window Application
m Forms with many different input and output types
m Contains Graphical User Interfaces (GUI)
m GUIs make the input and output more user friendly!
m Message boxes
• Within the System.Windows.Forms namespace
• Used to prompt or display information to the user
Typical C# Window Application
r Program specifications (optional)
r Library imports (optional)
using System;
using System.Windows.Forms;
r Class and namespace definitions
class HelloWorld : System.Windows.Forms.Form
static void Main(string[] args)
Application.Run(new HelloWorld());
This code creates a Window Form of default
size 300x300, with no title text.
It uses the default HelloWorld constructor
inherited from the Form class
Typical C# Window Application (cont’d)
r Program specifications (optional)
r Library imports (optional)
using System;
using System.Drawing;
using System.Windows.Forms;
r Class and namespace definitions
class HelloWorld : System.Windows.Forms.Form
public HelloWorld() {
Size = new Size(300,100);
Text = “HelloWorld”;
static void Main(string[] args)
Application.Run(new HelloWorld());
Modify the Constructor so the window size is
300x100 with title text “HelloWorld”.
New library that
defines the Size
class!
Typical C# Window Application (cont’d)
r Program specifications (optional)
r Library imports (optional)
using System;
using System.Drawing;
using System.Windows.Forms;
r Class and namespace definitions
public class HelloWorld : Form
public HelloWorld() {
Size = new Size(300, 100);
Text = “HelloWorld”;
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
g.DrawString(“Hello World ”, Font, Brushes.Blue, 30, 30);
static void Main(string[] args)
Application.Run(new HelloWorld());
r Program specifications (optional)
r Library imports (optional)
using System;
using System.Drawing;
using System.Windows.Forms;
r Class and namespace definitions
public class HelloWorld : Form
public HelloWorld() {
Size = new Size(300, 100);
Text = “HelloWorld”;
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
g.DrawString(“Hello World ”, Font, Brushes.Blue, 30, 30);
static void Main(string[] args)
Application.Run(new HelloWorld());
Class Form comes from
the
System.Windows.Forms
library
Typical C# Window Applications
r Program specifications (optional)
r Library imports (optional)
using System;
using System.Drawing;
using System.Windows.Forms;
r Class and namespace definitions
public class HelloWorld : System.Windows.Forms.Form
public HelloWorld() {
Size = new Size(300, 100);
Text = “HelloWorld”;
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
g.DrawString(“Hello World ”, Font, Brushes.Blue, 30, 30);
static void Main(string[] args)
Application.Run(new HelloWorld());
Class Form comes from
the
System.Windows.Forms
library
Challenges for Window Applications
r What are the inputs?
m Many more possible input sources (e.g., mouse click,
keyboard press, repainting a window)
m Some comes directly from user actions, some are indirect
and implicit
r How to react to these inputing “events”?
m Need to write what we call “event handlers”
- OnPaint acts like an event handler for the “Paint” event request.
r What are the outputs?
m Display different GUI widgets with proper layout
m Graphics programming
m Animation
Do the easy one first!
Basic Graphics: Where to Paint?
r A graphics context is a
drawing surface, the
drawing area of a form or
a panel
r A Graphics object
manages a graphics
context; thus drawing
actions are always like:
Graphics g;
// get g
g.DrawAction()…
x-axis
y-axis
+x
+y
(x, y)
Graphics coordinate system. Units are measured in pixels.
When to Paint?
r There are two cases:
m when a control becomes visible/resized etc, it will
receive a Paint event from the run time system
m Or if you call Invalidate, it will generate a
Paint event as well
• for example you want to redraw after you update in a
timer handler
How to Handle the Paint Event?
r A form has a virtual event handler OnPaint() for the Paint event; thus
one way is to override the virtual event handler OnPaint(), e.g.,
protected override void OnPaint( PaintEventArgs e )
Graphics g = e.Graphics;
Pen pen = new Pen( Color.Blue );
g.DrawLine(pen, 0, 0, 150, 150);
r Another possibility is to write your own event handler to handle the
Paint event, e.g.,
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
Graphics g = e.Graphics;
Pen pen = new Pen( Color.Blue );
g.DrawLine(pen, 0, 0, 150, 150);
Drawing Lines, Rectangles, and Ovals
Graphics Drawing Methods and Descriptions.
Note: Many of these methods are overloaded—consult the documentation for a full listing.
DrawLine( Pen p, int x1, int y1, int x2, int y2 )
Draws a line from (x1, y1) to (x2, y2). The Pen determines the color, style and width of the
line.
DrawRectangle( Pen p, int x, int y, int width, int height )
Draws a rectangle of the specified width and height. The top-left corner of the rectangle is at point
(x, y). The Pen determines the color, style, and border width of the rectangle.
FillRectangle( Brush b, int x, int y, int width, int height )
Draws a solid rectangle of the specified width and height. The top-left corner of the rectangle is at
point (x, y). The Brush determines the fill pattern inside the rectangle.
DrawEllipse( Pen p, int x, int y, int width, int height )
Draws an ellipse inside a rectangle. The width and height of the rectangle are as specified, and its
top-left corner is at point (x, y). The Pen determines the color, style and border width of the
ellipse.
FillEllipse( Brush b, int x, int y, int width, int height )
Draws a filled ellipse inside a rectangle. The width and height of the rectangle are as specified,
and its top-left corner is at point (x, y). The Brush determines the pattern inside the ellipse.
Graphics methods that draw lines, rectangles and ovals.
Example: Drawing Ellipse
Ellipse bounded by a rectangle.
(x, y)
height
width
DrawEllipse( Pen p, int x, int y, int width, int height );
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LinesRectanglesO
vals.cs
1 // Figure 16.18 LinesRectanglesOvals.cs 2 // Demonstrating lines, rectangles and ovals. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // draws shapes on the Form 12 public class LinesRectanglesOvals : System.Windows.Forms.Form 13 { 14 private System.ComponentModel.Container components = null; 15 16 [STAThread] 17 static void Main() 18 { 19 Application.Run( new LinesRectanglesOvals() ); 20 } 21 22 // Visual Studio .NET generated code 23 24 protected override void OnPaint( 25 PaintEventArgs paintEvent ) 26 { 27 // get graphics object 28 Graphics g = paintEvent.Graphics; 29 SolidBrush brush = new SolidBrush( Color.Blue ); 30 Pen pen = new Pen( Color.AliceBlue ); 31 32 // create filled rectangle 33 g.FillRectangle( brush, 90, 30, 150, 90 ); 34
Drawing rectangle
on the screen
Drawing object
Coordinates for bounding
rectangle Rectangle’s width and height
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LinesRectanglesO
vals.cs
Program Output
35 // draw lines to connect rectangles 36 g.DrawLine( pen, 90, 30, 110, 40 ); 37 g.DrawLine( pen, 90, 120, 110, 130 ); 38 g.DrawLine( pen, 240, 30, 260, 40 ); 39 g.DrawLine( pen, 240, 120, 260, 130 ); 40 41 // draw top rectangle 42 g.DrawRectangle( pen, 110, 40, 150, 90 ); 43 44 // set brush to red 45 brush.Color = Color.Red; 46 47 // draw base Ellipse 48 g.FillEllipse( brush, 280, 75, 100, 50 ); 49 50 // draw connecting lines 51 g.DrawLine( pen, 380, 55, 380, 100 ); 52 g.DrawLine( pen, 280, 55, 280, 100 ); 53 54 // draw Ellipse outline 55 g.DrawEllipse( pen, 280, 30, 100, 50 ); 56 57 } // end method OnPaint 58 59 } // end class LinesRectanglesOvals
DrawLine takes a Pen and
two pairs of int s
Start and end
point of the line
Uses pen object to draw
Overloaded methods
DrawEllipse and
FillEllipse
Specify drawing object
Coordinates of the bounding
rectangle for the ellipse
Bounding rectangle’s
width and height
Drawing Arcs
Fig. 16.16 Positive and negative arc angles.
Positive Arc Negative Arc
Properties of an Arc
m Starting angle
m Arc angle
m Bounding rectangle
Drawing Arcs
Graphics Methods And Desc riptions
Note: Many of these methods are overloaded—consult the documentation for a complete listing.
DrawArc( Pen p, int x, int y, int width, int height,
int startAngle, int sweepAngle )
Draws an arc of an ellipse, beginning from angle startAngle (in degrees) and sweeping
sweepAngle degrees. The ellipse is defined by a bounding rectangle of width w, height h and
upper-left corner (x,y). The Pen determines the color, border width and style of the arc.
DrawPie( Pen p, int x, int y, int width, int height,
int startAngle, int sweepAngle )
Draws a pie section of an ellipse, beginning from angle startAngle (in degrees) and sweeping
sweepAngle degrees. The ellipse is defined by a bounding rectangle of width w, height h and
upper-left corner (x,y). The Pen determines the color, border width and style of the arc.
FillPie( Brush b, int x, int y, int width, int height,
int startAngle, int sweepAngle )
Functions similarly to DrawPie, except draws a solid arc (i.e., a sector). The Brush determines
the fill pattern for the solid arc.
Fig. 16.17 Graphics methods for d rawing arcs.
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawShapes.cs
1 // Fig. 16.21: DrawShapes.cs 2 // Drawing various shapes on a form. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.Drawing.Drawing2D; 11 12 // draws shapes with different brushes 13 public class DrawShapesForm : System.Windows.Forms.Form 14 { 15 private System.ComponentModel.Container components = null; 16 17 [STAThread] 18 static void Main() 19 { 20 Application.Run( new DrawShapesForm() ); 21 } 22 23 // Visual Studio .NET generated code 24 25 // draw various shapes on form 26 private void DrawShapesForm_Paint( 27 object sender, System.Windows.Forms.PaintEventArgs e ) 28 { 29 // references to object we will use 30 Graphics graphicsObject = e.Graphics; 31 32 // ellipse rectangle and gradient brush 33 Rectangle drawArea1 = 34 new Rectangle( 5, 35, 30, 100 );
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawShapes.cs
35 LinearGradientBrush linearBrush = 36 new LinearGradientBrush( drawArea1, Color.Blue, 37 Color.Yellow, LinearGradientMode.ForwardDiagonal ); 38 39 // pen and location for red outline rectangle 40 Pen thickRedPen = new Pen( Color.Red, 10 ); 41 Rectangle drawArea2 = new Rectangle( 80, 30, 65, 100 ); 42 43 // bitmap texture 44 Bitmap textureBitmap = new Bitmap( 10, 10 ); 45 46 // get bitmap graphics 47 Graphics graphicsObject2 = 48 Graphics.FromImage( textureBitmap ); 49 50 // brush and pen used throughout program 51 SolidBrush solidColorBrush = 52 new SolidBrush( Color.Red ); 53 Pen coloredPen = new Pen( solidColorBrush ); 54 55 // draw ellipse filled with a blue-yellow gradient 56 graphicsObject.FillEllipse( 57 linearBrush, 5, 30, 65, 100 ); 58 59 // draw thick rectangle outline in red 60 graphicsObject.DrawRectangle( thickRedPen, drawArea2 ); 61 62 // fill textureBitmap with yellow 63 solidColorBrush.Color = Color.Yellow; 64 graphicsObject2.FillRectangle( 65 solidColorBrush, 0, 0, 10, 10 ); 66
LinearGradientBrush allow
users to draw color gradient
Argument takes a Rectangle
Two Colors
An enumeration
LinearGradientMode
The defining line for
LinearGradientBrush linearBrush
Specifies the gradient’s direction
Draw an ellipse with linearBrush
Argument specify a red line
10 pixels wide
New Bitmap 10 pixels
wide 10 pixels tall
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawShapes.cs
67 // draw small black rectangle in textureBitmap 68 coloredPen.Color = Color.Black; 69 graphicsObject2.DrawRectangle( 70 coloredPen, 1, 1, 6, 6 ); 71 72 // draw small blue rectangle in textureBitmpa 73 solidColorBrush.Color = Color.Blue; 74 graphicsObject2.FillRectangle( 75 solidColorBrush, 1, 1, 3, 3 ); 76 77 // draw small red square in textureBitmap 78 solidColorBrush.Color = Color.Red; 79 graphicsObject2.FillRectangle( 80 solidColorBrush, 4, 4, 3, 3 ); 81 82 // create textured brush and 83 // display textured rectangle 84 TextureBrush texturedBrush = 85 new TextureBrush( textureBitmap ); 86 graphicsObject.FillRectangle( 87 texturedBrush, 155, 30, 75, 100 ); 88 89 // draw pie-shaped arc in white 90 coloredPen.Color = Color.White; 91 coloredPen.Width = 6; 92 graphicsObject.DrawPie( 93 coloredPen, 240, 30, 75, 100, 0, 270 ); 94 95 // draw lines in green and yellow 96 coloredPen.Color = Color.Green; 97 coloredPen.Width = 5; 98 graphicsObject.DrawLine( 99 coloredPen, 395, 30, 320, 150 ); 100
TextureBrush fills interior
of shape with image
texturedBrush fill rectangle
with Bitmap
DrawPie with coloredPen ,
coordinates and sizes
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawShapes.cs
Program Output
101 // draw a rounded, dashed yellow line 102 coloredPen.Color = Color.Yellow; 103 coloredPen.DashCap = ( DashCap )LineCap.Round; 104 coloredPen.DashStyle = DashStyle.Dash; 105 graphicsObject.DrawLine( 106 coloredPen, 320, 30, 395, 150 ); 107 108 } // end method DrawShapesForm_Paint 109 110 } // end class DrawShapesForm
Set DashCap property of coloredPen
to member of DashCap enumeration
DashCap enumeration specify
styles for endpoints
Set DashStyle property of
coloredPen to DashStyle.Dash
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawStarsForm.cs
1 // Fig. 16.22: DrawStarsForm.cs 2 // Using paths to draw stars on the form. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.Drawing.Drawing2D; 11 12 // draws randomly colored stars 13 public class DrawStarsForm : System.Windows.Forms.Form 14 { 15 private 16 System.ComponentModel.Container components = null; 17 18 [STAThread] 19 static void Main() 20 { 21 Application.Run( new DrawStarsForm() ); 22 } 23 24 // Visual Studio .NET generated code 25 26 // create path and draw stars along it 27 private void DrawStarsForm_Paint( 28 object sender, System.Windows.Forms.PaintEventArgs e ) 29 { 30 Graphics graphicsObject = e.Graphics; 31 Random random = new Random(); 32 SolidBrush brush = 33 new SolidBrush( Color.DarkMagenta ); 34
2001 Prentice Hall, Inc.
All rights reserved.
Outline
DrawStarsForm.cs
35 // x and y points of the path 36 int[] xPoints = 37 { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; 38 int[] yPoints = 39 { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; 40 41 // create graphics path for star; 42 GraphicsPath star = new GraphicsPath(); 43 44 // translate the origin to (150, 150) 45 graphicsObject.TranslateTransform( 150, 150 ); 46 47 // create star from series of points 48 for ( int i = 0; i <= 8; i += 2 ) 49 star.AddLine( xPoints[ i ], yPoints[ i ], 50 xPoints[ i + 1 ], yPoints[ i + 1 ] ); 51 52 // close the shape 53 star.CloseFigure(); 54 55 // rotate the origin and draw stars in random colors 56 for ( int i = 1; i <= 18; i++ ) 57 { 58 graphicsObject.RotateTransform( 20 ); 59 60 brush.Color = Color.FromArgb( 61 random.Next( 200, 255 ), random.Next( 255 ), 62 random.Next( 255 ), random.Next( 255 ) ); 63 64 graphicsObject.FillPath( brush, star ); 65 } 66 67 } // end method DrawStarsForm_Paint 68 69 } // end class DrawStarsForm
Set the origin of the
Graphics object
Int array representing
coordinates points for the star
Create lines to connect the points
of the star and store them in star
CloseFigure to complete the shape
Method AddLine to
append line to the shape
AddLine adds a line from the
previous point to current point
Loop to draw star 18 times,
rotating around the origin
Method FillPath draws a
filled star with Brush
Randomly generate
colors for the stars
Class View and Object Browser
Object Browser when user selects Object from Time1.cs. (part 1)