Download Graphical User Interface, Lecture Slide - Computer Science and more Slides C programming in PDF only on Docsity!
CS 112 Introduction to
Programming
Lecture #25:
Graphical User Interface; Events
http://flint.cs.yale.edu/cs112/
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());
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”
r What are the outputs?
m Display different GUI widgets with proper layout
m Graphics programming
m Animation
GUI Programming: Basic Concepts
r A GUI component is a class that implements the
IComponent interface
m a control , such as a button or label, is a component with a
graphical part
r Some components, which we call containers , can
contain other components
m some examples are Form, Panel, GroupBox
r Components can generate events to which event
handler can respond to
GUI Components/Controls
r Components and Controls are organized into
an inheritance class hierarchy so that they can
easily share characteristics
r Each component/control defines some
m properties
m methods
m events
r The easiest way to add components and
controls to a program is to use VS .NET
ToolBox
Components and Controls
for Windows Forms
Example: Windows.Forms.Form
Form Properties,
Methods and Events
Description / Delegate and Event Arguments
Common Properties AcceptButton Which button will be clicked when Enter is pressed. AutoScroll Whether scrollbars appear when needed (if data fills more than one screen). CancelButton Button that is clicked when the Escape key is pressed. FormBorderStyle Border of the form (e.g., none, single, 3D, sizable). Font (^) Font of text displayed on the form, as well as the default font of controls added to the form. Text Text in the form’s title bar. Common Methods Close (^) Closes form and releases all resources. A closed form cannot be reopened. Hide Hides form (does not release resources). Show Displays a hidden form. Common Events (Delegate EventHandler, event arguments EventArgs) Load Occurs before a form is shown. This event is the default when the form is double-clicked in the Visual Studio .NET designer. Paint Each time it is redrawn
Click When a user clicks on the form
Event, Event Handler and Delegate
r Events, e.g.,
m a window becomes visible
m a graphical button is clicked
m a keyboard key is pressed
m the mouse is moved
m a mouse button is clicked
m the mouse is dragged
m a timer expires
r Event handler
m a method that processes an event and performs tasks
r In a control, there is one delegate for each event it can
generate
m a delegate of an event is an object which references (a list of )
methods, i.e., event handlers
Event-Handling Model
Fig. 12.5 Event-handling model using delegate.
Object A raises event E Delegate for event E
Handler 1 for event E
Handler 3 for event E
Handler 2 for event E
calls
calls
Window Application Revisited
using System; using System.Drawing; using System.Windows.Forms;
public class HelloWorld : System.Windows.Forms.Form
public HelloWorld() {
Text = “SimpleEventExample”;
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());
We can replace OnPaint method with an event handler for the Paint event.
OnPaint via Event Handling
using System; using System.Drawing; using System.Windows.Forms;
public class HelloWorld : System.Windows.Forms.Form
public HelloWorld() {
Text = “SimpleEventExample”;
this.Paint += new PaintEventHandler(Form1_Paint);
private void Form1_Paint(object sender, PaintEventArgs e) {
Graphics g = e.Graphics;
g.DrawString("hello, world", Font, Brushes.Aqua, 30, 30);
// 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());
Window Application w. Event Handling
using System; using System.Drawing; using System.Windows.Forms;
public class HelloWorld : System.Windows.Forms.Form
public HelloWorld() {
Text = “SimpleEventExample”;
this.Click += new System.EventHandler(MyForm_Click);
// protected override void OnPaint(PaintEventArgs e) { // Graphics g = e.Graphics; // g.DrawString(“Hello World ”, Font, Brushes.Blue, 30, 30); // }
private void MyForm_Click(object sender, System.EventArgs e) {
MessageBox.Show( "Form was pressed" );
static void Main(string[] args) {
Application.Run(new HelloWorld());
TextBoxes
r Provide an area for text input
m You can specify that a textbox is a password
textbox
T e x t B o x P r o p e r t i e s a n d Ev e n t s
D e sc rip t io n / D e le g a t e a n d Ev e n t A r g u m e n t s
Common Properties A c c e p t s R e t u r n (^) If t r u e , pressing Enter creates a new line if textbox spans multiple lines. If f a l s e^ , pressing Enter^ clicks the default button of the form. M u l t i l i n e If t r u e , textbox can span multiple lines. Default is f a l s e. P a s s w o r d C h a r Single character to display instead of typed text, making the T e x t B o x a password box. If no character is specified, T e x t b o x displays the typed text. R e a d O n l y If t r u e , T e x t B o x h a s a gray background and its text cannot be edited. Default is f a l s e. S c r o l l B a r s For multiline textboxes, indicates which scrollbars appear (n o n e , h o r i z o n t a l , v e r t i c a l o r b o t h ). T e x t (^) The text to be displayed in the text box. C o m m o n E v e n t s (Delegate (^) E v e n t H a n d l e r , event arguments E v e n t A r g s ) T e x t C h a n g e d Raised when text changes in T e x t B o x (the user added or deleted characters). Default event when this control is double clicked in the designer.
Fig. 1 2. 1 6 T e x t B o x p ro p e rtie s a n d e v e n t s.
Buttons
r Control to trigger a specific action
r Derived from ButtonBase
Button properties and
events
Description / Delegate and Event Arguments
Common Properties
Text Text displayed on the Button face.
Common Events (Delegate EventHandler, event arguments EventArgs)
Click Raised when user clicks the control. Default event when this control is
double clicked in the designer.
Fig. 12.17 Button properties and events.
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LabelTextBoxButt
onTest.cs
1 // Fig. 12.18: LabelTextBoxButtonTest.cs 2 // Using a Textbox, Label and Button to display 3 // the hidden text in a password box. 4 5 using System; 6 using System.Drawing; 7 using System.Collections; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Data; 11 12 // namespace contains our form to display hidden text 13 namespace LabelTextBoxButtonTest 14 { 15 /// 16 /// form that creates a password textbox and 17 /// a label to display textbox contents 18 /// 19 public class LabelTextBoxButtonTest : 20 System.Windows.Forms.Form 21 { 22 private System.Windows.Forms.Button displayPasswordButton; 23 private System.Windows.Forms.Label displayPasswordLabel; 24 private System.Windows.Forms.TextBox inputPasswordTextBox; 25 26 /// 27 /// Required designer variable. 28 /// 29 private System.ComponentModel.Container components = null; 30 31 // default contructor 32 public LabelTextBoxButtonTest() 33 { 34 InitializeComponent(); 35 }
Visual Studio .NET adds
comments to our code
Visual Studio .NET inserts declarations
for the control we added to the form ;The
IDE manages these declaration
Declare reference components (an array)
Method InitializeComponent creates
components and controls in the form and
sets their properties
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LabelTextBoxButt
onTest.cs
37 /// 38 /// Clean up any resources being used. 39 /// 40 protected override void Dispose( bool disposing ) 41 { 42 if ( disposing ) 43 { 44 if ( components != null ) 45 { 46 components.Dispose(); 47 } 48 } 49 50 base.Dispose( disposing ); 51 } 52 53 #region Windows Form Designer generated code 54 /// 55 /// Required method for Designer support - do not modify 56 /// the contents of this method with the code editor. 57 /// 58 private void InitializeComponent() 59 { 60 this.displayPasswordButton = 61 new System.Windows.Forms.Button(); 62 this.inputPasswordTextBox = 63 new System.Windows.Forms.TextBox(); 64 this.displayPasswordLabel = 65 new System.Windows.Forms.Label(); 66 this.SuspendLayout(); 67
Method Dispose cleans up allocated
resources
#region preprocessor directives allow
collapsible code in Visual Studio .NET
Create new objects for the
control we added
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LabelTextBoxButt
onTest.cs
69 // displayPasswordButton 70 // 71 this.displayPasswordButton.Location = 72 new System.Drawing.Point( 96, 96 ); 73 this.displayPasswordButton.Name = 74 "displayPasswordButton"; 75 this.displayPasswordButton.TabIndex = 1; 76 this.displayPasswordButton.Text = "Show Me"; 77 this.displayPasswordButton.Click += 78 new System.EventHandler( 79 this.displayPasswordButton_Click ); 80 81 // 82 // inputPasswordTextBox 83 // 84 this.inputPasswordTextBox.Location = 85 new System.Drawing.Point( 16, 16 ); 86 this.inputPasswordTextBox.Name = 87 "inputPasswordTextBox"; 88 this.inputPasswordTextBox.PasswordChar = '*'; 89 this.inputPasswordTextBox.Size = 90 new System.Drawing.Size( 264, 20 ); 91 this.inputPasswordTextBox.TabIndex = 0; 92 this.inputPasswordTextBox.Text = ""; 93 94 // 95 // displayPasswordLabel 96 // 97 this.displayPasswordLabel.BorderStyle = 98 System.Windows.Forms.BorderStyle.Fixed3D; 99 this.displayPasswordLabel.Location = 100 new System.Drawing.Point( 16, 48 ); 101 this.displayPasswordLabel.Name = 102 "displayPasswordLabel";
Set the Name, PasswordChar
and Text properties for
inputPasswordTextBox
Visual Studio .NET register
the event handler for us
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LabelTextBoxButt
onTest.cs
103 this.displayPasswordLabel.Size = 104 new System.Drawing.Size( 264, 23 ); 105 this.displayPasswordLabel.TabIndex = 2; 106 107 // 108 // LabelTextBoxButtonTest 109 // 110 this.AutoScaleBaseSize = 111 new System.Drawing.Size( 5, 13 ); 112 this.ClientSize = 113 new System.Drawing.Size( 292, 133 ); 114 this.Controls.AddRange( 115 new System.Windows.Forms.Control[] { 116 this.displayPasswordLabel, 117 this.inputPasswordTextBox, 118 this.displayPasswordButton}); 119 this.Name = "LabelTextBoxButtonTest"; 120 this.Text = "LabelTextBoxButtonTest"; 121 this.ResumeLayout( false ); 122 123 } // end method InitializeComponent 124 125 // end collapsible region started on line 53 126 #endregion 127 128 /// 129 /// The main entry point for the application. 130 /// 131 [STAThread] 132 static void Main() 133 { 134 Application.Run( new LabelTextBoxButtonTest() ); 135 } 136
#endregion signal the end
of the collapsible region
2001 Prentice Hall, Inc.
All rights reserved.
Outline
LabelTextBoxButt
onTest.cs
Program Output
137 // display user input on label 138 protected void displayPasswordButton_Click( 139 object sender, System.EventArgs e ) 140 { 141 // text has not changed 142 displayPasswordLabel.Text = 143 inputPasswordTextBox.Text; 144 } 145 146 } // end class LabelTextBoxButtonTest 147 148 } // end namespace LabelTextBoxButtonTest
To show the text, set
displayPasswordLabel’s Text to
inputPasswordTextBox’s Text
PictureBox
r Displays an image
r Read image from file:
Image.FromFile() method (need to add
System.IO name space)
PictureBox
p roperties and events
Desc ription / Delegate and Event Arguments
Common Properties
Image Image to display in the PictureBox.
SizeMode Enumeration that controls image sizing and positioning. Values
Normal (default), StretchImage, AutoSize and
CenterImage. Normal puts image in top-left corner of
PictureBox and CenterImage puts image in middle (both cut
off image if too large). StretchImage resizes image to fit in
PictureBox. AutoSize resizes PictureBox to hold image.
Common Events (Delegate EventHandler, event arguments EventArgs)
Click Raised when user clicks the control. Default event when this control is
double clicked in the designer.
Fig. 12.27 PictureBox p roperties and events.
2001 Prentice Hall, Inc.
All rights reserved.
Outline
PictureBoxTest.c
s
1 // Fig. 12.28: PictureBoxTest.cs 2 // Using a PictureBox to display images. 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.IO; 11 12 /// form to display different images when clicked 13 public class PictureBoxTest : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.PictureBox imagePictureBox; 16 private System.Windows.Forms.Label promptLabel; 17 18 private int imageNum = -1; 19 20 /// The main entry point for the application. 21 [STAThread] 22 static void Main() 23 { 24 Application.Run( new PictureBoxTest() ); 25 } 26 27 // change image whenever PictureBox clicked 28 private void imagePictureBox_Click( 29 object sender, System.EventArgs e ) 30 { 31 imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2 32
PictureBox imagePicture
use to display
one of three bitmap images
Includes instructions Click
On Picture Box to View
Images
To respond to the Click event
Store the image we want to display
Modulus calculation insures that
number is between 0 and 2
2001 Prentice Hall, Inc.
All rights reserved.
Outline
PictureBoxTest.c
s
Program Output
33 // create Image object from file, display on PictureBox 34 imagePictureBox.Image = Image.FromFile( 35 Directory.GetCurrentDirectory() + "\images\image" + 36 imageNum + ".bmp" ); 37 } 38
39 }Set the // end Image class property of PictureBoxTest
imagePictureBox to an Image
Method FromFile which
takes a string and creates
an Image object
Method GetCurrentDirectory of Class Directory
returns current directory of file as a string
Use imageNum to append
the correct number
Layout Management
r Size structure
m Allow for specifying size range
- MinimumSize and MaximumSize property
r Location structure
m Specifies upper-left corner of the control, relative to container
r Anchor and dock
m Anchor
- Anchored control stays at a specific location (relative to parent)
- constant distance from specified location
- unanchored control moves relative to the position
m Dock
- allows control to spread itself along and entire side
The Effect of Anchoring
Fig. 12.11 Anchoring demonstration.
Constant distance
to left and top sides
Before resize After resize
2001 Prentice Hall, Inc.
All rights reserved.
Outline
GroupBoxPanelExa
mple.cs
1 // Fig. 12.22: GroupBoxPanelExample.cs 2 // Using GroupBoxes and Panels to hold buttons. 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 /// form to display a groupbox versus a panel 12 public class GroupBoxPanelExample : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Button hiButton; 15 private System.Windows.Forms.Button byeButton; 16 private System.Windows.Forms.Button leftButton; 17 private System.Windows.Forms.Button rightButton; 18 19 private System.Windows.Forms.GroupBox mainGroupBox; 20 private System.Windows.Forms.Label messageLabel; 21 private System.Windows.Forms.Panel mainPanel; 22 23 private System.ComponentModel.Container components = null; 24 25 // Visual Studio .NET-generated Dispose method 26 27 [STAThread] 28 static void Main() 29 { 30 Application.Run( new GroupBoxPanelExample() ); 31 } 32
GroupBox (name mainGroupBox )
Panel (name mainPanel)
Control AutoScroll
property set to TRUE
2001 Prentice Hall, Inc.
All rights reserved.
Outline
GroupBoxPanelExa
mple.cs
33 // event handlers to change messageLabel 34 35 // event handler for hi button 36 private void hiButton_Click( 37 object sender, System.EventArgs e ) 38 { 39 messageLabel.Text= "Hi pressed"; 40 } 41 42 // event handler for bye button 43 private void byeButton_Click( 44 object sender, System.EventArgs e ) 45 { 46 messageLabel.Text = "Bye pressed"; 47 } 48 49 // event handler for far left button 50 private void leftButton_Click( 51 object sender, System.EventArgs e ) 52 { 53 messageLabel.Text = "Far left pressed"; 54 } 55 56 // event handler for far right button 57 private void rightButton_Click( 58 object sender, System.EventArgs e ) 59 { 60 messageLabel.Text = "Far right pressed"; 61 } 62 63 } // end class GroupBoxPanelExample
Represent event handlers
hiButton and byeButton
belong to GroupBox
Panel has two buttons,
leftButton and rightButton
Line messageLabel added to
customize the text
2001 Prentice Hall, Inc.
All rights reserved.
Outline
GroupBoxPanelExa
mple.cs
Program Output
hiButton_Click
leftButton_Click rightButton _Click
Keyboard Event Handling
r Two types of key events
m Delegate KeyEventHandler
• Handles two sub types of events: KeyUp or KeyDown
m Delegate KeyPressEventHandler
• Handles one type of event: KeyPress
KeyEventHandler
Keyboard Events, Delegates and Event Arguments
Key Events (Delegate
KeyEventHandler, event arguments
KeyEventArgs)
KeyDown Raised when key is initially pushed down.
KeyUp Raised when key is released.
Class KeyEventArgs Properties
Alt Indicates whether the Alt key was pressed.
Control Indicates whether the Control key was pressed.
Shift Indicates whether the Shift key was pressed.
Handled Whether the event was handled.
KeyCode Returns the key code for the key, as a Keys
enumeration. This does not include modifier key
information. Used to test for a specific key.
KeyData Returns the key code as a Keys enumeration,
combined with modifier information. Used to
determine all information about the key pressed.
KeyValue Returns the key code as an int, rather than as a Keys
enumeration. Used to obtain a numeric representation
of the key pressed.
Modifiers Returns a Keys enumeration for any modifier keys
pressed ( Alt , Control and Shift ). Used to determine
modifier key information only.
KeyPressEventHandler
Keyboard Events, Delegates and
Event Arguments
Key Events (Delegate
KeyPressEventHandler, event
arguments KeyPressEventArgs)
KeyPress Raised when key is pressed. Occurs repeatedly while
key is held down, at a rate specified by the operating
system.
Class KeyPressEventArgs
Properties
KeyChar Returns the ASCII character for the key pressed.
Handled Whether or not the KeyPress event was handled.
See KeyDemo
2001 Prentice Hall, Inc.
All rights reserved.
Outline
KeyDemo.cs
1 // Fig. 12.32: KeyDemo.cs 2 // Displaying information about the key the user pressed. 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 // form to display key press 12 // information--contains two labels 13 public class KeyDemo : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.Label charLabel; 16 private System.Windows.Forms.Label keyInfoLabel; 17 18 private System.ComponentModel.Container components = null; 19 20 /// The main entry point for the application. 21 [STAThread] 22 static void Main() 23 { 24 Application.Run( new KeyDemo() ); 25 } 26 27 // display the character pressed using key char 28 protected void KeyDemo_KeyPress( 29 object sender, System.Windows.Forms.KeyPressEventArgs e ) 30 { 31 charLabel.Text = "Key pressed: " + e.KeyChar; 32 } 33
Forms contain two Label s
Label for key pressed
Label for modifier information
KeyPress event handler
Accesses the KeyChar property
of the KeyPressEventArgs object
Key pressed as a char
Display the key pressed
2001 Prentice Hall, Inc.
All rights reserved.
Outline
KeyDemo.cs
34 // display modifier keys, key code, key data and key value 35 private void KeyDemo_KeyDown( 36 object sender, System.Windows.Forms.KeyEventArgs e ) 37 { 38 keyInfoLabel.Text = 39 "Alt: " + ( e.Alt? "Yes" : "No") + '\n' + 40 "Shift: " + ( e.Shift? "Yes" : "No" ) + '\n' + 41 "Ctrl: " + ( e.Control? "Yes" : "No" ) + '\n' + 42 "KeyCode: " + e.KeyCode + '\n' + 43 "KeyData: " + e.KeyData + '\n' + 44 "KeyValue: " + e.KeyValue; 45 } 46 47 // clear labels when key released 48 private void KeyDemo_KeyUp( 49 object sender, System.Windows.Forms.KeyEventArgs e ) 50 { 51 keyInfoLabel.Text = ""; 52 charLabel.Text = ""; 53 }
KeyEventArgs object
KeyCode returns the key pressed
without modifier keys
information
KeyData property returns the keys pressed
with modifier keys
KeyValue returns the key code as an
integer; the integer value is the Windows
virtual key code
KeyUp event handler clears both labels
Backup Slides
GUI
r Introduction: Components and controls; Event handling model
r Controls
m Common properties
m Basic controls
- Label, textbox, checkbox, radiobutton, picturebox, LinkLabels, ListBox,
CheckedListBox
m Containers
- Groupbox, panel: for layout
- Tab controls
- Multiple-document interface windows
m Event handling: mouse, keyboard
m More controls
- Menus
- ComboBoxes
- TreeView control
r Graphics
m Color, font
m Lines, arcs, polygons
m Brush specification
r Multimedia