CSL12GUI1
CSL12GUI1
12.1 Introduction
1
3
12.1 Introduction
Button Label Menu Bar TextBox Scrollbar
12.1 Introduction
TextBox An area in which the user inputs data from the keyboard. The area also
can display information.
Button An area that triggers an event when clicked.
CheckBox A GUI control that is either selected or not selected.
ComboBox A drop-down list of items from which the user can make a selection,
by clicking an item in the list or by typing into the box, if permitted.
ListBox An area in which a list of items is displayed from which the user can
make a selection by clicking once on any element. Multiple elements
can be selected.
Panel A container in which components can be placed.
ScrollBar Allows the user to access a range of values that cannot normally fit in
its container.
Fig. 12.2 Som e b a sic G UI c o m p o ne nts.
2
5
• WinForms
– Create GUIs for programs
– Element on the desktop
– Represented by:
• Dialog
• Window
• MDI window
• Component
– Class that implements IComponent interface
– Lacks visual parts
• Control
– Component with graphical part
• Such as button or label
– Are visible
• Event
– Generated by movement from mouse or keyboard
– Event handlers performs action
• Specifics written by programmer
3
7
4
9
10
5
11
• Event handler
– Must have same signature as corresponding delegate
– Two object reference are passed in
– ControlName_EventName
– Must be registered with delegate object
• Add event handlers to the delegate’s invocation list
– New delegate object for each event handler
• Event multicasting
– Have multiple handlers for one event
– Order called for event handlers is indeterminate
12
Events icon
List of events
supported by
control
Selected event
Current even
handler (none)
Event
description
6
13
1 // Fig. 12.7: SimpleEventExample.cs Outline
2 // Using Visual Studio .NET to create event handlers.
3
4 using System;
5 using System.Drawing; SimpleEventExamp
6 using System.Collections; le.cs
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 // program that shows a simple event handler
12 public class MyForm : System.Windows.Forms.Form
13 {
14 private System.ComponentModel.Container components = null;
15
16 // Visual Studio .NET generated code
17
18 [STAThread]
19 static void Main()
20 { Class EventArgs is base class for
21 Application.Run(
Create an event handler new MyForm() );
22 }
objects with event information
23
24 // Visual Studio .NET creates an empty handler,
25 // we write definition: show message box when form clicked
26 private void MyForm_Click( object sender, System.EventArgs e )
27 {
28 MessageBox.Show( "Form was pressed" );
29 } Reference to an event
30 Reference
Signature to
of the
the object that
event handler
31 } // end class MyForm raised the eventarguments
(sender)object (e)
14
Outline
SimpleEventExamp
le.cs
Program Output
7
15
16
Event name
8
17
• Common properties
– Derive from class Control
– Text property
• Specifies the text that appears on a control
– Focus method
• Transfers the focus to a control
• Becomes active control
– TabIndex property
• Order in which controls are given focus
• Automatically set by Visual Studio .NET
– Enable property
• Indicate a control’s accessibility
18
• Visibility control
– Hide control from user
• Or use method Hide
• Anchor property
– Anchoring control to specific location
• Constant distance from specified location
– Unanchored control moves relative to the position
– Docking allows control to spread itself along and entire side
– Both options refer to the parent container
• Size structure
– Allow for specifying size range
• MinimumSize and MaximumSize property
9
19
20
Constant distance
to left and top sides
10
21
Click down-arrow
in Anchor property
to display
anchoring window
22
11
23
24
• Labels
– Provide text instruction
• Read only text
– Defined with class Label1
• Derived from class Control
• Textbox
– Class TextBox
– Area for text input
• Password textbox
12
25
• Button
– Control to trigger a specific action
• Checkboxes or radio buttons
– Derived from ButtonBase
26
13
27
AcceptsReturn If true, pressing Enter creates a new line if textbox spans multiple
lines. If false, pressing Enter clicks the default button of the form.
Multiline If true, textbox can span multiple lines. Default is false.
PasswordChar Single character to display instead of typed text, making the
TextBox a password box. If no character is specified, Textbox
displays the typed text.
ReadOnly If true, TextBox has a gray background and its text cannot be
edited. Default is false.
ScrollBars For multiline textboxes, indicates which scrollbars appear (none,
horizontal, vertical or both).
Text The text to be displayed in the text box.
Common Events (Delegate EventHandler, event arguments EventArgs)
TextChanged Raised when text changes in TextBox (the user added or deleted
characters). Default event when this control is double clicked in the
designer.
Fig . 12.16 TextBox p ro p e rtie s a nd e v e nts.
28
14
29
1 // Fig. 12.18: LabelTextBoxButtonTest.cs Outline
2 // Using a Textbox, Label and Button to display
3 // the hidden text in a password box.
4
5 using System; LabelTextBoxButt
6 using System.Drawing; onTest.cs
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 Visual Studio .NET adds
14 { comments to our code
15 /// <summary>
16 /// form that creates a password textbox and
17 /// a label to display textbox contents
18 /// </summary>
19 public class LabelTextBoxButtonTest : Visual
The IDEStudio
manages
.NETthese
inserts
declaration
declarations
20 System.Windows.Forms.Form for the control we added to the form
21 {
22 private System.Windows.Forms.Button displayPasswordButton;
23 private System.Windows.Forms.Label displayPasswordLabel;
24 private System.Windows.Forms.TextBox inputPasswordTextBox;
25 Declare referenceReference
components (an array)
is null
26 /// <summary>
27 /// Required designer variable.
28 /// </summary>
29 private System.ComponentModel.Container components = null;
30
31 // default contructor Method InitializeComponent creates
32 public LabelTextBoxButtonTest() Constructor forand
thecontrols
form is created for us
33 { components in the form and
34 InitializeComponent(); sets their properties © 2002 Prentice Hall.
35 }
All rights reserved.
30
36 Outline
37 /// <summary>
38 /// Clean up any resources being used.
39 /// </summary>
40 protected override void Dispose( bool disposing ) LabelTextBoxButt
41 { onTest.cs
42 if ( disposing )
43 {
44 if ( components != null )
Method Dispose cleans up allocated
45 { resources
46 components.Dispose();
47 }
48 }
49 #region preprocessor directives allow
50 base.Dispose( disposing );
51 } collapsible code in Visual Studio .NET
52
53 #region Windows Form Designer generated code
54 /// <summary>
55 /// Required method for Designer support - do not modify
56 /// the contents of this method with the code editor.
57 /// </summary>
58 private void InitializeComponent()
59 {
60 this.displayPasswordButton =
61 new System.Windows.Forms.Button();
Create new objects for the
62 this.inputPasswordTextBox = control we added
63 new System.Windows.Forms.TextBox();
64 this.displayPasswordLabel =
65 new System.Windows.Forms.Label();
66 this.SuspendLayout();
67
15
31
68 // Outline
69 // displayPasswordButton
70 //
71 this.displayPasswordButton.Location =
72 new System.Drawing.Point( 96, 96 ); LabelTextBoxButt
73 this.displayPasswordButton.Name = onTest.cs
74 "displayPasswordButton";
75 this.displayPasswordButton.TabIndex = 1;
76 this.displayPasswordButton.Text = "Show Me";
77 this.displayPasswordButton.Click += Visual Studio .NET register
78 new System.EventHandler(
79 this.displayPasswordButton_Click );
the event handler for us
80
81 //
82 // inputPasswordTextBox
83 //
84 this.inputPasswordTextBox.Location =
85 new System.Drawing.Point( 16, 16 ); Set the Name, PasswordChar
86 this.inputPasswordTextBox.Name = and Text properties for
87 "inputPasswordTextBox";
88 this.inputPasswordTextBox.PasswordChar = '*'; inputPasswordTextBox
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"; © 2002 Prentice Hall.
All rights reserved.
32
103 this.displayPasswordLabel.Size = Outline
104 new System.Drawing.Size( 264, 23 );
105 this.displayPasswordLabel.TabIndex = 2;
106
107 // LabelTextBoxButt
108 // LabelTextBoxButtonTest onTest.cs
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
#endregion signal the end
127 of the collapsible region
128 /// <summary>
129 /// The main entry point for the application.
130 /// </summary>
131 [STAThread]
132 static void Main()
133 {
134 Application.Run( new LabelTextBoxButtonTest() );
135 }
136
© 2002 Prentice Hall.
All rights reserved.
16
33
137 // display user input on label Outline
138 protected void displayPasswordButton_Click(
139 object sender, System.EventArgs e )
140 {
To show the text, set
141 // text has not changed User must program this lineLabelTextBoxButt
displayPasswordLabel’s manually
Text to
142 displayPasswordLabel.Text = inputPasswordTextBox’sonTest.cs
Text
143 inputPasswordTextBox.Text;
144 } Create an empty event handler named
145 displayPasswordButton_Click
146 } // end class LabelTextBoxButtonTest
147
148 } // end namespace LabelTextBoxButtonTest
Program Output
34
17
35
GroupBoxProperties Description
Common Properties
36
AutoScroll Whether scrollbars appear when the Panel is too small to hold its
controls. Default is false.
BorderStyle Border of the Panel (default None; other options are Fixed3D and
FixedSingle).
Controls The controls that the Panel contains.
Fig. 12.20 Panel properties.
18
37
Controls inside
panel panel
panel
scrollbars
38
1 // Fig. 12.22: GroupBoxPanelExample.cs Outline
2 // Using GroupBoxes and Panels to hold buttons.
3
4 using System;
5 using System.Drawing; GroupBoxPanelExa
6 using System.Collections; mple.cs
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; GroupBox (name mainGroupBox)
16 private System.Windows.Forms.Button leftButton;
17 private System.Windows.Forms.Button rightButton; Panel (name mainPanel)
18
19 private System.Windows.Forms.GroupBox mainGroupBox; Control AutoScroll
20 private System.Windows.Forms.Label messageLabel;
21 private System.Windows.Forms.Panel mainPanel; property set to TRUE
messageLabel is initially blank
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
19
39
33 // event handlers to change messageLabel Outline
34
35 // event handler for hi button
36 private void hiButton_Click(
37 object sender, System.EventArgs e ) GroupBoxPanelExa
38 { mple.cs
39 messageLabel.Text= "Hi pressed"; hiButton and byeButton
40 }
41
belong to GroupBox
42 // event handler for bye button
43 private void byeButton_Click(
44 object sender, System.EventArgs e )
45 {
46 messageLabel.Text = "Bye pressed";
Represent event handlers
47 }
48
49 // event handler for far left button Line messageLabel added to
50 private void leftButton_Click(
51 object sender, System.EventArgs e )
customize the text
52 {
53 messageLabel.Text = "Far left pressed"; Panel has two buttons,
54 } leftButton and rightButton
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
40
Outline
GroupBoxPanelExa
hiButton_Click mple.cs
Program Output
leftButton_Click rightButton_Click
20
41
• State buttons
– On/off or true/false state
– Derived from class ButtonBase
• CheckBox
– No restriction on usage
• RadioButton
– Grouped together
– Only one can be true
– Mutually exclusive options
42
21
43
1 // Fig. 12.24: CheckBoxTest.cs Outline
2 // Using CheckBoxes to toggle italic and bold styles.
3
4 using System;
5 using System.Drawing; CheckBoxTest.cs
6 using System.Collections;
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 /// form contains checkboxes to allow When program start, both
12 /// the user to modify sample text Checkbox is unchecked
13 public class CheckBoxTest : System.Windows.Forms.Form
14 { Text property set to Bold
15 private System.Windows.Forms.CheckBox boldCheckBox;
16 private System.Windows.Forms.CheckBox italicCheckBox;
17
18 private System.Windows.Forms.Label outputLabel; The Label
Text OutputLabel
property set to Italic is labeled
19 Watch the font style change
20 private System.ComponentModel.Container components = null;
21
22 // Visual Studio .NET-generated Dispose method
23
24 /// The main entry point for the application.
25 [STAThread]
26 static void Main()
27 {
28 Application.Run( new CheckBoxTest() );
29 }
30
44
31 // make text bold if not bold, Outline
32 // if already bold make not bold
33 private void boldCheckBox_CheckedChanged(
34 object sender, System.EventArgs e )
35 { CheckBoxTest.cs
36 outputLabel.Font =
37 new Font( outputLabel.Font.Name, Font constructor takes in the
38 outputLabel.Font.Size, font name, size, and style
39 outputLabel.Font.Style ^ FontStyle.Bold );
40 }
41 Style is a member of the
42 //Style
make property
text italic if not italic,
43 // if already Font Style
object’s
italic can usenot
make Style
bitwise
property
operators
italic is
FontStyle enumeration
44
itself is read-only
set when object is created
private void italicCheckBox_CheckedChanged(
45 object sender, System.EventArgs e )
46 {
47 outputLabel.Font =
48 new Font( outputLabel.Font.Name,
49 outputLabel.Font.Size,
50 outputLabel.Font.Style ^ FontStyle.Italic );
51 }
52
53 } // end class CheckBoxTest
22
45
Outline
CheckBoxTest.cs
Program Output
46
23
47
1 // Fig. 12.26: RadioButtonsTest.cs Outline
2 // Using RadioButtons to set message window options.
3
4 using System;
5 using System.Drawing; RadioButtonsTest
6 using System.Collections; .cs
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 /// form contains several radio buttons--user chooses one
12 /// from each group to create a custom MessageBox
13 public class RadioButtonsTest : System.Windows.Forms.Form
14 { Label is used to prompt user
15 private System.Windows.Forms.Label promptLabel; Label is used to display
16 private System.Windows.Forms.Label displayLabel;
17 private System.Windows.Forms.Button displayButton;
which button was pressed
18 Display the text Display
19 private System.Windows.Forms.RadioButton questionButton;
20 private System.Windows.Forms.RadioButton informationButton;
21 private System.Windows.Forms.RadioButton exclamationButton;
22 private System.Windows.Forms.RadioButton errorButton; RadioButtons are
23 private System.Windows.Forms.RadioButton retryCancelButton; created for the
24 private System.Windows.Forms.RadioButton yesNoButton;
25 private System.Windows.Forms.RadioButton yesNoCancelButton;
enumeration options
26 private System.Windows.Forms.RadioButton okCancelButton;
27 private System.Windows.Forms.RadioButton okButton;
To store user’s choice of One event handling exists for
28 private System.Windows.Forms.RadioButton
options iconType is created. all the
Theradio buttons in
enumeration
29 abortRetryIgnoreButton; Object iconType is a
30
groupBox1 and groupBox2
name indicate which
MessageBoxIcon
enumeration display
button to
31 private System.Windows.Forms.GroupBox groupBox2;
32 private System.Windows.Forms.GroupBox groupBox1;
33
34 private MessageBoxIcon iconType = MessageBoxIcon.Error;
© 2002 Prentice Hall.
All rights reserved.
48
35 private MessageBoxButtons buttonType =
The enumeration
To storebuttonType
user’s choice
Outline
36 MessageBoxButtons.OK; Object is of
a
37 name indicate
optionswhich
buttonType isenumeration
MessageBoxButtom created
38 /// The main entry point for the application.
39 [STAThread]
button to display RadioButtonsTest
40 static void Main() .cs
41 { Handlers compare the sender object
42 with every radio button to determine
Application.Run( new RadioButtonsTest() );
43 }
44
which button was selected
45 // change button based on option chosen by sender
46 private void buttonType_CheckedChanged(
47 object sender, System.EventArgs e ) Each radio button generates
48 { a CheckedChanged when
49 if ( sender == okButton ) // display OK button
50 buttonType = MessageBoxButtons.OK; clicked
51
52 // display OK and Cancel buttons
53 else if ( sender == okCancelButton )
54 buttonType = MessageBoxButtons.OKCancel;
55
56 // display Abort, Retry and Ignore buttons
57 else if ( sender == abortRetryIgnoreButton )
58 buttonType = MessageBoxButtons.AbortRetryIgnore;
59
60 // display Yes, No and Cancel buttons
61 else if ( sender == yesNoCancelButton )
62 buttonType = MessageBoxButtons.YesNoCancel;
63
64 // display Yes and No buttons
65 else if ( sender == yesNoButton )
66 buttonType = MessageBoxButtons.YesNo;
67
68 // only one option left--display
69 // Retry and Cancel buttons © 2002 Prentice Hall.
All rights reserved.
24
49
70 else Outline
71 Handlers compare the
buttonType = MessageBoxButtons.RetryCancel; sender object
72
73 } // end method
with every
buttonType_CheckedChanged
radio button to determine
74 which button was selected RadioButtonsTest
75 // change icon based on option chosen by sender .cs
76 private void iconType_CheckedChanged(
77 object sender, System.EventArgs e )
78 {
79 if ( sender == errorButton ) // display error icon
80 iconType = MessageBoxIcon.Error;
81
82 // display exclamation point
83 else if ( sender == exclamationButton )
84 iconType = MessageBoxIcon.Exclamation;
85
86 // display information icon
87 else if ( sender == informationButton )
88 iconType = MessageBoxIcon.Information;
89
90 else // only one option left--display question mark
91 iconType = MessageBoxIcon.Question;
92
93 } // end method iconType_CheckedChanged
94
95 // display MessageBox and button user pressed
96 protected void displayButton_Click(
97 object sender, System.EventArgs e ) Result
Clickofhandler
messagefor
box
displayButton
is a
98 { DialogResult
creates a MessageBox
enumeration
99 DialogResult result =
100
SwitchMessageBox.Show(
statement tests for"This
the result and
is Your Custom MessageBox.",
101 set displayLabel.Text appropriately
"Custom MessageBox", buttonType, iconType, 0, 0 );
102
103 // check for dialog result and display it in label
104 switch ( result ) © 2002 Prentice Hall.
All rights reserved.
50
105 { Outline
106 case DialogResult.OK:
107 displayLabel.Text = "OK was pressed.";
108 break;
109 RadioButtonsTest
110 case DialogResult.Cancel: .cs
111 displayLabel.Text = "Cancel was pressed.";
112 break;
113
114 case DialogResult.Abort:
115 displayLabel.Text = "Abort was pressed.";
116 break; The result input will help
117 determine which text to display
118 case DialogResult.Retry:
119 displayLabel.Text = "Retry was pressed.";
among the cases
120 break;
121
122 case DialogResult.Ignore:
123 displayLabel.Text = "Ignore was pressed.";
124 break;
125
126 case DialogResult.Yes:
127 displayLabel.Text = "Yes was pressed.";
128 break;
129
130 case DialogResult.No:
131 displayLabel.Text = "No was pressed.";
132 break;
133
134 } // end switch
135
136 } // end method displayButton_Click
137
138 } // end class RadioButtonsTest
© 2002 Prentice Hall.
All rights reserved.
25
51
Outline
RadioButtonsTest
.cs
Program Output
52
Outline
RadioButtonsTest
Information icon type Question icon type .cs
Program Output
26
53
12.8 PictureBoxes
• Class PictureBox
– Displays an image
• Image set by object of class Image.
– The Image property sets the Image object to use
– SizeMode property sets how the image is displayed
54
12.8 PictureBoxes
27
55
1 // Fig. 12.28: PictureBoxTest.cs Outline
2 // Using a PictureBox to display images.
3
4 using System;
5 using System.Drawing; PictureBoxTest.c
6 using System.Collections; s
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10 using System.IO;
11
PictureBox imagePicture
12 /// form to display different images when clicked use to display
13 public class PictureBoxTest : System.Windows.Forms.Form one of three bitmap images
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. Includes instructions Click
21 [STAThread]
22 static void Main()
On Picture Box to View
23 { Images
24 Application.Run(
Store new PictureBoxTest()
the image we want to display );
25 }
26
27 // change image whenever PictureBox clicked To respond to the Click event
28 private void imagePictureBox_Click( Modulus calculation insures that
29 object sender, System.EventArgs e ) number is between 0 and 2
30 {
31 imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2
32
56
33 // create Image object from file, display on PictureBox Outline
34 imagePictureBox.Image = Image.FromFile(
35 Directory.GetCurrentDirectory() + "\\images\\image" +
36 imageNum + ".bmp" );
37 } PictureBoxTest.c
38 Method GetCurrentDirectory of Class Directory s
39 Set//the
} Use
Image
end imageNum
property
class toofappend
PictureBoxTest Method
returns current directory of file FromFile which
as a string
imagePictureBox
the correct number
to an Image takes a string and creates
an Image object
Program Output
28
57
• Class MouseEventArgs
– Contain coordinates of the mouse pointer
– The mouse pressed
– Number of clicks
– Number of notches the wheel turned
– Passing mouse event
– Mouse event-handling methods take an object and
MouseEventArgs object as argument
– The Click event uses delegate EventHandler and event
arguments EventArgs
58
M o u se Ev e n t s, D e le g a t e s
a n d Ev e n t A rg u m e n t s
M ouse Events (D elegate
E v e nt Han d le r , event
argum ents E ve n tA r gs )
M o u se Ent e r Raised if the mouse cursor enters the area of the control.
M o u se Lea v e Raised if the mouse cursor leaves the area of the control.
M ouse Events (D elegate
M o u se Eve n tH a nd l er ,
event argum ents
M o u se Eve n tA r gs )
M o u se Dow n Raised if the mouse button is pressed while its cursor is over the area of the
control.
M o u se Hov e r Raised if the mouse cursor hovers over the area of the control.
M o u se Mov e Raised if the mouse cursor is m oved while in the area of the control.
M o u se Up Raised if the mouse button is released when the cursor is over the area of the
control.
Class M ou s eEv en t A rg s
Properties
B u t to n M ouse button that was pressed (l ef t , r ig ht , mi d d le or n o ne ).
C l i ck s The num ber of tim es the m ouse button w as clicked.
X The x-coordinate of the event, relative to the com ponent.
Y The y-coordinate of the event, relative to the com ponent.
Fig . 1 2.2 9 M o u se e v e n t s, d e le g a t e s a n d e v e n t a rg u m e n t s.
29
59
1 // Fig 12.30: Painter.cs Outline
2 // Using the mouse to draw on a form.
3
4 using System;
5 using System.Drawing; Painter.cs
6 using System.Collections;
7 using System.ComponentModel;
8 using System.Windows.Forms;
9 using System.Data;
10
11 /// creates a form as a drawing surface Creates variable shouldPaint to
12 public class Painter : System.Windows.Forms.Form determine whether to draw on
13 {
14 bool shouldPaint = false; // whether to paint the form
15
16 /// The main entry point for the application.
17 [STAThread]
18 static void Main()
19 {
20 Application.Run( new Painter() );
21 }
22
23 // should paint after mouse button has been pressed
24 private void Painter_MouseDown(
The event handler for
25 object sender, System.Windows.Forms.MouseEventArgs eevent ) MouseDown
26 { shouldPaint is set to true
27 shouldPaint = true; Mouse cursor will
28 } drawwhen this event occurs
29
30 // stop painting when mouse button released
31 private void Painter_MouseUp( The event handler of
32 object sender, System.Windows.Forms.MouseEventArgs e )mouse
shouldPaint set to false, event MouseUp
33 {
34 shouldPaint = false;
cursor will not draw
35 } © 2002 Prentice Hall.
All rights reserved.
60
36 Outline
37 // draw circle whenever mouse button
38 // moves (and mouse is down)
39 protected void Painter_MouseMove(
40 object sender, System.Windows.Forms.MouseEventArgs e ) Painter.cs
41 { Creates
Program
the graphic
will draw only if
42 if ( shouldPaint )
43 { object
shouldPaint
for the formis true
44 Graphics graphics = CreateGraphics(); Method
ProvidesFillEllipse
method for draws a circle at every
45 graphics.FillEllipse( point theCreate
drawing mouse
variousnew SolidBrush
cursor
shapesmoves overobject
and by
46 new SolidBrush( Color.BlueViolet ),
47 e.X, e.Y, 4, 4 );
passing
shouldPaint is the
true constructor a Color
48 } value
49
Coordinates of x and y and the pixels height
Structure Color contain
SolidBrush
andnumerous
widthobject determines
are supplied to the parameter list
50 } // end Painter_MouseMove
51 predefined color the
constants
color of the shape drawn
52 } // end class Painter
Program Output
30
61
• Key events
– Control that inherits from System.Windows.Forms.Control
– Delegate KeyPressEventHandler
• Event argument KeyPressEventArgs
• KeyPress
– ASCII character pressed
– No modifier keys
– Delegate KeyEventHandler
• Event argument KeyEventArgs
• KeyUp or KeyDown
– Special modifier keys
• Key enumeration value
62
31
63
1 // Fig. 12.32: KeyDemo.cs Outline
2 // Displaying information about the key the user pressed.
3
4 using System;
5 using System.Drawing; KeyDemo.cs
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 {
Label for key pressed
Forms contain
Initially empty two Labels
15 private System.Windows.Forms.Label charLabel;
16 private System.Windows.Forms.Label keyInfoLabel; Label for modifier information
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 } KeyPress event
Accesses
If key pressed ishandlerthe KeyChar property
not ASCII,
26
27 // display the character pressed using keycharLabel
char
of the KeyPressEventArgs object
remains empty
28 protected void KeyDemo_KeyPress(
29 object sender, System.Windows.Forms.KeyPressEventArgs e )
30 { Key pressed as a char
31 charLabel.Text = "Key pressed: " + e.KeyChar;
32 }
33
Display the key pressed
© 2002 Prentice Hall.
All rights reserved.
64
34 // display modifier keys, key code, key data and key value Outline
35 private void KeyDemo_KeyDown(
36 object sender, System.Windows.Forms.KeyEventArgs e )
37 {
38 keyInfoLabel.Text = Uses Alt, Shift, and Control KeyDemo.cs
39 "Alt: " + ( e.Alt ? "Yes" : properties
"No") + '\n' +
KeyEventArgs object
40 "Shift: " + ( e.Shift ? "Yes" KeyCode
: "No" ) returns
+ '\n'the
a+Keys
key enumeration
pressed
This block test for special
41 "Ctrl: " + ( e.Control ? "Yes"Displays
: "No" )the
+ KeyCode,
'\n' + KeyData, and bool if matched
42
KeyData
converted
without
"KeyCode: " + e.KeyCode + '\n'KeyValue
+
property
modifier
into returns
a string
keys akeys,
Keys
information
using ToString
return
enumeration properties
with data about modifier keys
43 "KeyData: " + e.KeyData + '\n' +
44 "KeyValue: " + e.KeyValue;
45 }
46 KeyValue
Integer valuereturns
is the the key code
Windows as ankey
virtual integer
code
47 // clear labels when key released KeyUp event handler clears both labels
48 private void KeyDemo_KeyUp(
49 object sender, System.Windows.Forms.KeyEventArgs e )
50 {
51 keyInfoLabel.Text = "";
52 charLabel.Text = "";
53 }
32
65
Outline
33