Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 12 - Graphical User Interface Concepts: Part 1

Similar presentations


Presentation on theme: "Chapter 12 - Graphical User Interface Concepts: Part 1"— Presentation transcript:

1 Chapter 12 - Graphical User Interface Concepts: Part 1
Outline Introduction Windows Forms Event-Handling Model Basic Event Handling Control Properties and Layout Labels, TextBoxes and Buttons GroupBoxes and Panels CheckBoxes and RadioButtons PictureBoxes Mouse Event Handling Keyboard Event Handling

2 Graphical user interface
12.1 Introduction Graphical user interface Allow interaction with program visually Give program distinct look and feel Built from window gadgets Is an object, accessed via keyboard or mouse

3 12.1 Introduction Button Label Menu Bar TextBox Scrollbar Fig Sample Internet Explorer window with GUI components.

4 12.1 Introduction

5 12.2 Windows Forms WinForms Create GUIs for programs
Element on the desktop Represented by: Dialog Window MDI window

6 12.2 Windows Forms Component Control Event
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

7 12.2 Windows Forms Fig Components and controls for Windows Forms.

8 12.2 Windows Forms

9 12.3 Event-Handling Model GUIs are event driven Event handlers
Methods that process events and perform tasks. Associated delegate Objects that reference methods Contain lists of method references Must have same signature Intermediaries for objects and methods Signature for control’s event handler

10 12.3 Event-Handling Model 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 Fig Event-handling model using delegates.

11 12.3.1 Basic Event Handling Event handler Event multicasting
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 12.3.1 Basic Event Handling Events icon
List of events supported by control Selected event Current even handler (none) Event description Fig Events section of the Properties window.

13 Class EventArgs is base class for objects with event information
1 // Fig. 12.7: SimpleEventExample.cs 2 // Using Visual Studio .NET to create event handlers. 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 // program that shows a simple event handler 12 public class MyForm : System.Windows.Forms.Form 13 { private System.ComponentModel.Container components = null; 15 // Visual Studio .NET generated code 17 [STAThread] static void Main() { Application.Run( new MyForm() ); } 23 // Visual Studio .NET creates an empty handler, // we write definition: show message box when form clicked private void MyForm_Click( object sender, System.EventArgs e ) { MessageBox.Show( "Form was pressed" ); } 30 31 } // end class MyForm SimpleEventExample.cs Class EventArgs is base class for objects with event information Create an event handler Reference to the object that raised the event (sender) Signature of the event handler Reference to an event arguments object (e)

14 SimpleEventExample.cs Program Output

15 12.3.1 Basic Event Handling Class name List of events
Fig List of Form events.

16 12.3.1 Basic Event Handling Event name Event delegate
Event argument class Fig Details of Click event.

17 12.4 Control Properties and Layout
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 12.4 Control Properties and Layout
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

19 12.4 Control Properties and Layout

20 12.4 Control Properties and Layout
Before resize After resize Constant distance to left and top sides Fig Anchoring demonstration.

21 12.4 Control Properties and Layout
Darkened bar indicates to which wall control is anchored Click down-arrow in Anchor property to display anchoring window Fig Manipulating the Anchor property of a control.

22 12.4 Control Properties and Layout
Control expands along top portion of the form Fig Docking demonstration.

23 12.4 Control Properties and Layout

24 12.5 Labels, TextBoxes and Buttons
Provide text instruction Read only text Defined with class Label1 Derived from class Control Textbox Class TextBox Area for text input Password textbox

25 12.5 Labels, TextBoxes and Buttons
Control to trigger a specific action Checkboxes or radio buttons Derived from ButtonBase

26 12.5 Labels TextBoxes and Buttons

27 12.5 Labels TextBoxes and Buttons

28 12.5 Labels TextBoxes and Buttons

29 Visual Studio .NET adds comments to our code
1 // Fig : 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 { /// <summary> /// form that creates a password textbox and /// a label to display textbox contents /// </summary> public class LabelTextBoxButtonTest : System.Windows.Forms.Form { private System.Windows.Forms.Button displayPasswordButton; private System.Windows.Forms.Label displayPasswordLabel; private System.Windows.Forms.TextBox inputPasswordTextBox; 25 /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; 30 // default contructor public LabelTextBoxButtonTest() { InitializeComponent(); } LabelTextBoxButtonTest.cs Visual Studio .NET adds comments to our code The IDE manages these declaration Visual Studio .NET inserts declarations for the control we added to the form Declare reference components (an array) Reference is null Method InitializeComponent creates components and controls in the form and sets their properties Constructor for the form is created for us

30 Method Dispose cleans up allocated resources
36 /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if ( disposing ) { if ( components != null ) { components.Dispose(); } } 49 base.Dispose( disposing ); } 52 #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.displayPasswordButton = new System.Windows.Forms.Button(); this.inputPasswordTextBox = new System.Windows.Forms.TextBox(); this.displayPasswordLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); 67 LabelTextBoxButtonTest.cs Method Dispose cleans up allocated resources #region preprocessor directives allow collapsible code in Visual Studio .NET Create new objects for the control we added

31 Visual Studio .NET register the event handler for us
// // displayPasswordButton // this.displayPasswordButton.Location = new System.Drawing.Point( 96, 96 ); this.displayPasswordButton.Name = "displayPasswordButton"; this.displayPasswordButton.TabIndex = 1; this.displayPasswordButton.Text = "Show Me"; this.displayPasswordButton.Click += new System.EventHandler( this.displayPasswordButton_Click ); 80 // // inputPasswordTextBox // this.inputPasswordTextBox.Location = new System.Drawing.Point( 16, 16 ); this.inputPasswordTextBox.Name = "inputPasswordTextBox"; this.inputPasswordTextBox.PasswordChar = '*'; this.inputPasswordTextBox.Size = new System.Drawing.Size( 264, 20 ); this.inputPasswordTextBox.TabIndex = 0; this.inputPasswordTextBox.Text = ""; 93 // // displayPasswordLabel // this.displayPasswordLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.displayPasswordLabel.Location = new System.Drawing.Point( 16, 48 ); this.displayPasswordLabel.Name = "displayPasswordLabel"; LabelTextBoxButtonTest.cs Visual Studio .NET register the event handler for us Set the Name, PasswordChar and Text properties for inputPasswordTextBox

32 #endregion signal the end of the collapsible region
this.displayPasswordLabel.Size = new System.Drawing.Size( 264, 23 ); this.displayPasswordLabel.TabIndex = 2; 106 // // LabelTextBoxButtonTest // this.AutoScaleBaseSize = new System.Drawing.Size( 5, 13 ); this.ClientSize = new System.Drawing.Size( 292, 133 ); this.Controls.AddRange( new System.Windows.Forms.Control[] { this.displayPasswordLabel, this.inputPasswordTextBox, this.displayPasswordButton}); this.Name = "LabelTextBoxButtonTest"; this.Text = "LabelTextBoxButtonTest"; this.ResumeLayout( false ); 122 } // end method InitializeComponent 124 // end collapsible region started on line 53 #endregion 127 /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run( new LabelTextBoxButtonTest() ); } 136 LabelTextBoxButtonTest.cs #endregion signal the end of the collapsible region

33 LabelTextBoxButtonTest.cs Program Output
// display user input on label protected void displayPasswordButton_Click( object sender, System.EventArgs e ) { // text has not changed displayPasswordLabel.Text = inputPasswordTextBox.Text; } 145 } // end class LabelTextBoxButtonTest 147 148 } // end namespace LabelTextBoxButtonTest To show the text, set displayPasswordLabel’s Text to inputPasswordTextBox’s Text Create an empty event handler named displayPasswordButton_Click User must program this line manually LabelTextBoxButtonTest.cs Program Output

34 Arrange components on a GUI
12.6 GroupBoxes and Panels Arrange components on a GUI GroupBoxes can display a caption Text property determines its caption Panels can have scrollbar View additional controls inside the Panel

35 12.6 GroupBoxes and Panels

36 12.6 GroupBoxes and Panels

37 12.6 GroupBoxes and Panels Controls inside panel panel
panel scrollbars Fig Creating a Panel with scrollbars.

38 GroupBox (name mainGroupBox)
1 // Fig : 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 { private System.Windows.Forms.Button hiButton; private System.Windows.Forms.Button byeButton; private System.Windows.Forms.Button leftButton; private System.Windows.Forms.Button rightButton; 18 private System.Windows.Forms.GroupBox mainGroupBox; private System.Windows.Forms.Label messageLabel; private System.Windows.Forms.Panel mainPanel; 22 private System.ComponentModel.Container components = null; 24 // Visual Studio .NET-generated Dispose method 26 [STAThread] static void Main() { Application.Run( new GroupBoxPanelExample() ); } 32 GroupBoxPanelExample.cs GroupBox (name mainGroupBox) Panel (name mainPanel) Control AutoScroll property set to TRUE messageLabel is initially blank

39 hiButton and byeButton belong to GroupBox
// event handlers to change messageLabel 34 // event handler for hi button private void hiButton_Click( object sender, System.EventArgs e ) { messageLabel.Text= "Hi pressed"; } 41 // event handler for bye button private void byeButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Bye pressed"; } 48 // event handler for far left button private void leftButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Far left pressed"; } 55 // event handler for far right button private void rightButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Far right pressed"; } 62 63 } // end class GroupBoxPanelExample GroupBoxPanelExample.cs hiButton and byeButton belong to GroupBox Represent event handlers Line messageLabel added to customize the text Panel has two buttons, leftButton and rightButton

40 GroupBoxPanelExample.cs Program Output
hiButton_Click leftButton_Click rightButton_Click

41 12.7 Checkboxes and RadioButtons
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 12.7 CheckBoxes and RadioButtons

43 When program start, both Checkbox is unchecked
1 // Fig : CheckBoxTest.cs 2 // Using CheckBoxes to toggle italic and bold styles. 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 contains checkboxes to allow 12 /// the user to modify sample text 13 public class CheckBoxTest : System.Windows.Forms.Form 14 { private System.Windows.Forms.CheckBox boldCheckBox; private System.Windows.Forms.CheckBox italicCheckBox; 17 private System.Windows.Forms.Label outputLabel; 19 private System.ComponentModel.Container components = null; 21 // Visual Studio .NET-generated Dispose method 23 /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new CheckBoxTest() ); } 30 CheckBoxTest.cs When program start, both Checkbox is unchecked Text property set to Bold The Label OutputLabel is labeled Watch the font style change Text property set to Italic

44 Font constructor takes in the font name, size, and style
// make text bold if not bold, // if already bold make not bold private void boldCheckBox_CheckedChanged( object sender, System.EventArgs e ) { outputLabel.Font = new Font( outputLabel.Font.Name, outputLabel.Font.Size, outputLabel.Font.Style ^ FontStyle.Bold ); } 41 // make text italic if not italic, // if already italic make not italic private void italicCheckBox_CheckedChanged( object sender, System.EventArgs e ) { outputLabel.Font = new Font( outputLabel.Font.Name, outputLabel.Font.Size, outputLabel.Font.Style ^ FontStyle.Italic ); } 52 53 } // end class CheckBoxTest CheckBoxTest.cs Font constructor takes in the font name, size, and style Font object’s Style property is set when object is created Style can use bitwise operators Style property itself is read-only Style is a member of the FontStyle enumeration

45 CheckBoxTest.cs Program Output
Result when bold is selected Result when both styles are selected

46 12.7 CheckBoxes and RadioButtons

47 Label is used to prompt user
1 // Fig : RadioButtonsTest.cs 2 // Using RadioButtons to set message window options. 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 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 { private System.Windows.Forms.Label promptLabel; private System.Windows.Forms.Label displayLabel; private System.Windows.Forms.Button displayButton; 18 private System.Windows.Forms.RadioButton questionButton; private System.Windows.Forms.RadioButton informationButton; private System.Windows.Forms.RadioButton exclamationButton; private System.Windows.Forms.RadioButton errorButton; private System.Windows.Forms.RadioButton retryCancelButton; private System.Windows.Forms.RadioButton yesNoButton; private System.Windows.Forms.RadioButton yesNoCancelButton; private System.Windows.Forms.RadioButton okCancelButton; private System.Windows.Forms.RadioButton okButton; private System.Windows.Forms.RadioButton abortRetryIgnoreButton; 30 private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox1; 33 private MessageBoxIcon iconType = MessageBoxIcon.Error; RadioButtonsTest.cs Label is used to prompt user Label is used to display which button was pressed Display the text Display RadioButtons are created for the enumeration options One event handling exists for all the radio buttons in groupBox1 and groupBox2 To store user’s choice of options iconType is created. The enumeration name indicate which button to display Object iconType is a MessageBoxIcon enumeration

48 The enumeration name indicate which button to display
private MessageBoxButtons buttonType = MessageBoxButtons.OK; 37 /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new RadioButtonsTest() ); } 44 // change button based on option chosen by sender private void buttonType_CheckedChanged( object sender, System.EventArgs e ) { if ( sender == okButton ) // display OK button buttonType = MessageBoxButtons.OK; 51 // display OK and Cancel buttons else if ( sender == okCancelButton ) buttonType = MessageBoxButtons.OKCancel; 55 // display Abort, Retry and Ignore buttons else if ( sender == abortRetryIgnoreButton ) buttonType = MessageBoxButtons.AbortRetryIgnore; 59 // display Yes, No and Cancel buttons else if ( sender == yesNoCancelButton ) buttonType = MessageBoxButtons.YesNoCancel; 63 // display Yes and No buttons else if ( sender == yesNoButton ) buttonType = MessageBoxButtons.YesNo; 67 // only one option left--display // Retry and Cancel buttons The enumeration name indicate which button to display To store user’s choice of options buttonType is created Object buttonType is a MessageBoxButtom enumeration RadioButtonsTest.cs Handlers compare the sender object with every radio button to determine which button was selected Each radio button generates a CheckedChanged when clicked

49 Result of message box is a DialogResult enumeration
else buttonType = MessageBoxButtons.RetryCancel; 72 } // end method buttonType_CheckedChanged 74 // change icon based on option chosen by sender private void iconType_CheckedChanged( object sender, System.EventArgs e ) { if ( sender == errorButton ) // display error icon iconType = MessageBoxIcon.Error; 81 // display exclamation point else if ( sender == exclamationButton ) iconType = MessageBoxIcon.Exclamation; 85 // display information icon else if ( sender == informationButton ) iconType = MessageBoxIcon.Information; 89 else // only one option left--display question mark iconType = MessageBoxIcon.Question; 92 } // end method iconType_CheckedChanged 94 // display MessageBox and button user pressed protected void displayButton_Click( object sender, System.EventArgs e ) { DialogResult result = MessageBox.Show( "This is Your Custom MessageBox.", "Custom MessageBox", buttonType, iconType, 0, 0 ); 102 // check for dialog result and display it in label switch ( result ) Handlers compare the sender object with every radio button to determine which button was selected RadioButtonsTest.cs Result of message box is a DialogResult enumeration Click handler for displayButton creates a MessageBox Switch statement tests for the result and set displayLabel.Text appropriately

50 { case DialogResult.OK: displayLabel.Text = "OK was pressed."; break; 109 case DialogResult.Cancel: displayLabel.Text = "Cancel was pressed."; break; 113 case DialogResult.Abort: displayLabel.Text = "Abort was pressed."; break; 117 case DialogResult.Retry: displayLabel.Text = "Retry was pressed."; break; 121 case DialogResult.Ignore: displayLabel.Text = "Ignore was pressed."; break; 125 case DialogResult.Yes: displayLabel.Text = "Yes was pressed."; break; 129 case DialogResult.No: displayLabel.Text = "No was pressed."; break; 133 } // end switch 135 } // end method displayButton_Click 137 138 } // end class RadioButtonsTest The result input will help determine which text to display among the cases RadioButtonsTest.cs

51 RadioButtonsTest.cs Program Output
Radio button style allow user to select one per column Exclamation icon type Error icon type OKCancel button type OK button type

52 RadioButtonsTest.cs Program Output
Information icon type Question icon type AbortRetryIgnore button type YesNoCancel button type YesNo button type RetryCancel button type

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

55 PictureBox imagePicture use to display one of three bitmap images
1 // Fig : 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 { private System.Windows.Forms.PictureBox imagePictureBox; private System.Windows.Forms.Label promptLabel; 17 private int imageNum = -1; 19 /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new PictureBoxTest() ); } 26 // change image whenever PictureBox clicked private void imagePictureBox_Click( object sender, System.EventArgs e ) { imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2 32 PictureBoxTest.cs PictureBox imagePicture use to display one of three bitmap images Includes instructions Click On Picture Box to View Images Store the image we want to display To respond to the Click event Modulus calculation insures that number is between 0 and 2

56 PictureBoxTest.cs Program Output
// create Image object from file, display on PictureBox imagePictureBox.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\image" + imageNum + ".bmp" ); } 38 39 } // end class PictureBoxTest Method FromFile which takes a string and creates an Image object Set the Image property of imagePictureBox to an Image Method GetCurrentDirectory of Class Directory returns current directory of file as a string PictureBoxTest.cs Program Output Use imageNum to append the correct number

57 12.9 Mouse Event Handling 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 12.9 Mouse Event Handling

59 Creates variable shouldPaint to determine whether to draw on the form
1 // Fig 12.30: Painter.cs 2 // Using the mouse to draw 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 11 /// creates a form as a drawing surface 12 public class Painter : System.Windows.Forms.Form 13 { bool shouldPaint = false; // whether to paint 15 /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new Painter() ); } 22 // should paint after mouse button has been pressed private void Painter_MouseDown( object sender, System.Windows.Forms.MouseEventArgs e ) { shouldPaint = true; } 29 // stop painting when mouse button released private void Painter_MouseUp( object sender, System.Windows.Forms.MouseEventArgs e ) { shouldPaint = false; } Painter.cs Creates variable shouldPaint to determine whether to draw on the form The event handler for event MouseDown shouldPaint is set to true when this event occurs Mouse cursor will draw The event handler of event MouseUp shouldPaint set to false, mouse cursor will not draw

60 Painter.cs Program Output
36 // draw circle whenever mouse button // moves (and mouse is down) protected void Painter_MouseMove( object sender, System.Windows.Forms.MouseEventArgs e ) { if ( shouldPaint ) { Graphics graphics = CreateGraphics(); graphics.FillEllipse( new SolidBrush( Color.BlueViolet ), e.X, e.Y, 4, 4 ); } 49 } // end Painter_MouseMove 51 52 } // end class Painter Painter.cs Program Output Creates the graphic object for the form Program will draw only if shouldPaint is true Method FillEllipse draws a circle at every point the mouse cursor moves over and shouldPaint is true Provides method for drawing various shapes Create new SolidBrush object by passing the constructor a Color value Structure Color contain numerous predefined color constants SolidBrush object determines the color of the shape drawn Coordinates of x and y and the pixels height and width are supplied to the parameter list

61 12.10 Keyboard Event Handling
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 12.10 Keyboard Event Handling

63 Forms contain two Labels
1 // Fig : 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 { private System.Windows.Forms.Label charLabel; private System.Windows.Forms.Label keyInfoLabel; 17 private System.ComponentModel.Container components = null; 19 /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new KeyDemo() ); } 26 // display the character pressed using key char protected void KeyDemo_KeyPress( object sender, System.Windows.Forms.KeyPressEventArgs e ) { charLabel.Text = "Key pressed: " + e.KeyChar; } 33 KeyDemo.cs Label for key pressed Initially empty Forms contain two Labels Label for modifier information KeyPress event handler Accesses the KeyChar property of the KeyPressEventArgs object If key pressed is not ASCII, charLabel remains empty Key pressed as a char Display the key pressed

64 Uses Alt, Shift, and Control properties KeyEventArgs object KeyDemo.cs
// display modifier keys, key code, key data and key value private void KeyDemo_KeyDown( object sender, System.Windows.Forms.KeyEventArgs e ) { keyInfoLabel.Text = "Alt: " + ( e.Alt ? "Yes" : "No") + '\n' + "Shift: " + ( e.Shift ? "Yes" : "No" ) + '\n' + "Ctrl: " + ( e.Control ? "Yes" : "No" ) + '\n' + "KeyCode: " + e.KeyCode + '\n' + "KeyData: " + e.KeyData + '\n' + "KeyValue: " + e.KeyValue; } 46 // clear labels when key released private void KeyDemo_KeyUp( object sender, System.Windows.Forms.KeyEventArgs e ) { keyInfoLabel.Text = ""; charLabel.Text = ""; } Uses Alt, Shift, and Control properties KeyEventArgs object KeyDemo.cs Displays the KeyCode, KeyData, and KeyValue properties KeyCode returns the key pressed without modifier keys information KeyCode returns a Keys enumeration converted into a string using ToString This block test for special keys, return bool if matched KeyData property returns a Keys enumeration with data about modifier keys KeyValue returns the key code as an integer Integer value is the Windows virtual key code KeyUp event handler clears both labels

65 KeyDemo.cs Program Output
Keys enumeration can test for specific keys by comparing key pressed to KeyCode KeyDown event still raised so keyInfoLabel displays information KeyPress event was not engaged


Download ppt "Chapter 12 - Graphical User Interface Concepts: Part 1"

Similar presentations


Ads by Google