1 Chapter 13. Graphical User Interface Concepts: Part 1 Continue from previouse lecture 2007 Dr. Natheer Khasawneh 2 Basic GUI components Control Description Label An area in which icons or uneditable text can be displayed. 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. 13.2 Some basic GUI components. 2007 Dr. Natheer Khasawneh 3 Windows Forms • 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 2007 Dr. Natheer Khasawneh 4 Windows Forms Components and controls for Windows Forms. 2007 Dr. Natheer Khasawneh 5 Windows Forms Form Properties and Description / Delegate and Event Arguments Events 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. Fig. 13.4 Common Form properties and events. 2007 Dr. Natheer Khasawneh 6 Finding Events Class name F List of Form events. 2007 Dr. Natheer Khasawneh List of events 7 Finding Events Event name Event delegate Details of Click event. 2007 Dr. Natheer Khasawneh 8 Finding Events Argument class Event delegate Details of Click event. 2007 Dr. Natheer Khasawneh 9 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 2007 Dr. Natheer Khasawneh 10 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 2007 Dr. Natheer Khasawneh 11 13.4 Control Properties and Layout De sc rip tion Cla ss Control Pro p e rtie s a nd M etho d s Common Properties BackColor Background color of the control. BackgroundImage Background image of the control. Enabled Whether the control is enabled (i.e., if the user can interact with it). A disabled control will still be displayed, but “grayed-out”—portions of the control will become gray. Focused Whether a control has focus. (The control that is currently being used in some way.) Font Font used to display control’s Text. ForeColor Foreground color of the control. This is usually the color used to display the control’s Text property. TabIndex Tab order of the control. When the Tab key is pressed, the focus is moved to controls in increasing tab order. This order can be set by the programmer. TabStop If true, user can use the Tab key to select the control. Text Text associated with the control. The location and appearance varies with the type of control. TextAlign The alignment of the text on the control. One of three horizontal positions (left, center or right) and one of three vertical positions (top, middle or bottom). Visible Whether the control is visible. Common Methods Focus Transfers the focus to the control. Hide Hides the control (sets Visible to false). Show Shows the control (sets Visible to true). Fig. 12.10 C la ss Control p ro p e rtie s a nd m e tho d s. 2007 Dr. Natheer Khasawneh 12 13.4 Control Properties and Layout Before resize After resize Constant distance to left and top sides Fig. 13.11 Anchoring demonstration. 2007 Dr. Natheer Khasawneh 13 13.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. 13.12 Manipulating the Anchor property of a control. 2007 Dr. Natheer Khasawneh 14 13.4 Control Properties and Layout Control expands along top portion of the form Fig. 13.13 Docking demonstration. 2007 Dr. Natheer Khasawneh 15 13.4 Control Properties and Layout Common Layout Properties Description Common Properties Anchor Side of parent container at which to anchor control—values can be combined, such as Top, Left. Dock Side of parent container to dock control—values cannot be combined. DockPadding (for containers) Sets the dock spacing for controls inside the container. Default is zero, so controls appear flush against the side of the container. Location Location of the upper-left corner of the control, relative to it’s container. Size Size of the control. Takes a Size structure, which has properties Height and Width. MinimumSize, MaximumSize (for Windows Forms) The minimum and maximum size of the form. Fig. 13.14 Class Control layout properties. 2007 Dr. Natheer Khasawneh 16 13.5 Labels, TextBoxes and Buttons • Labels – Provide text instruction • Read only text – Defined with class Label1 • Derived from class Control • Textbox – Class TextBox – Area for text input • Password textbox 2007 Dr. Natheer Khasawneh 17 13.5 Labels, TextBoxes and Buttons • Button – Control to trigger a specific action • Checkboxes or radio buttons – Derived from ButtonBase 2007 Dr. Natheer Khasawneh 18 13.5 Labels TextBoxes and Buttons Label Description / Delegate and Event Arguments Properties Common Properties Font The font used by the text on the Label. Text The text to appear on the Label. TextAlign The alignment of the Label’s text on the control. One of three horizontal positions (left, center or right) and one of three vertical positions (top, middle or bottom). Fig. 13.15 Label properties. 2007 Dr. Natheer Khasawneh 19 13.5 Labels TextBoxes and Buttons TextBox Properties Description / Delegate and Event Arguments and Events Common Properties 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. 13.16 TextBox properties and events. 2007 Dr. Natheer Khasawneh 20 13.5 Labels TextBoxes and Buttons Button properties and Description / Delegate and Event Arguments events 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. 13.17 Button properties and events. 2007 Dr. Natheer Khasawneh 21 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Fig. 13.18: LabelTextBoxButtonTest.cs // Using a Textbox, Label and Button to display // the hidden text in a password box. using using using using using using Outline LabelTextBoxButt onTest.cs System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; // namespace contains our form to display hidden text namespace LabelTextBoxButtonTest Visual Studio .NET adds { comments to our code /// <summary> /// form that creates a password textbox and /// a label to display textbox contents /// </summary> Visual The IDE Studio manages .NETthese inserts declaration declarations public class LabelTextBoxButtonTest : System.Windows.Forms.Form for the control we added to the form { private System.Windows.Forms.Button displayPasswordButton; private System.Windows.Forms.Label displayPasswordLabel; private System.Windows.Forms.TextBox inputPasswordTextBox; Declare reference Reference components (an array) is null /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; // default contructor public LabelTextBoxButtonTest() { InitializeComponent(); } Method InitializeComponent creates Constructor forand thecontrols form is created for us components in the form and sets their properties 2007 Dr. Natheer Khasawneh 22 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if ( disposing ) { Method Dispose if ( components != null ) { components.Dispose(); } } base.Dispose( disposing ); } Outline LabelTextBoxButt onTest.cs cleans up allocated resources #region preprocessor directives allow collapsible code in Visual Studio .NET #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 = Create new objects new System.Windows.Forms.Button(); control we added this.inputPasswordTextBox = new System.Windows.Forms.TextBox(); this.displayPasswordLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); for the 2007 Dr. Natheer Khasawneh 23 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 // // 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 ); // // 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 = ""; // // displayPasswordLabel // this.displayPasswordLabel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.displayPasswordLabel.Location = new System.Drawing.Point( 16, 48 ); this.displayPasswordLabel.Name = "displayPasswordLabel"; Outline LabelTextBoxButt onTest.cs Visual Studio .NET register the event handler for us Set the Name, PasswordChar and Text properties for inputPasswordTextBox 2007 Dr. Natheer Khasawneh 24 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 Outline this.displayPasswordLabel.Size = new System.Drawing.Size( 264, 23 ); this.displayPasswordLabel.TabIndex = 2; // // 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 ); LabelTextBoxButt onTest.cs } // end method InitializeComponent // end collapsible region started on line 53 #endregion #endregion signal the end of the collapsible region /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run( new LabelTextBoxButtonTest() ); } 2007 Dr. Natheer Khasawneh 25 137 138 139 140 141 142 143 144 145 146 147 148 Outline // display user input on label protected void displayPasswordButton_Click( object sender, System.EventArgs e ) To show the text, set { User must program this lineLabelTextBoxButt manually displayPasswordLabel’s Text to // text has not changed displayPasswordLabel.Text = inputPasswordTextBox’sonTest.cs Text inputPasswordTextBox.Text; Create an empty event handler named } displayPasswordButton_Click } // end class LabelTextBoxButtonTest } // end namespace LabelTextBoxButtonTest Program Output 2007 Dr. Natheer Khasawneh 26 13.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 2007 Dr. Natheer Khasawneh 27 13.6 GroupBoxes and Panels GroupBox Properties Description Common Properties Controls The controls that the GroupBox contains. Text Text displayed on the top portion of the GroupBox (its caption). Fig. 13.19 GroupBox properties. 2007 Dr. Natheer Khasawneh 28 13.6 GroupBoxes and Panels Panel Properties Description Common Properties 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. 13.20 Panel properties. 2007 Dr. Natheer Khasawneh 29 13.6 GroupBoxes and Panels Controls inside panel panel panel scrollbars Fig. 13.21 Creating a Panel with scrollbars. 2007 Dr. Natheer Khasawneh 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // Fig. 13.22: GroupBoxPanelExample.cs // Using GroupBoxes and Panels to hold buttons. using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; GroupBoxPanelExa mple.cs /// form to display a groupbox versus a panel public class GroupBoxPanelExample : System.Windows.Forms.Form { private System.Windows.Forms.Button hiButton; GroupBox (name mainGroupBox) private System.Windows.Forms.Button byeButton; private System.Windows.Forms.Button leftButton; private System.Windows.Forms.Button rightButton; Panel (name mainPanel) private System.Windows.Forms.GroupBox mainGroupBox; private System.Windows.Forms.Label messageLabel; private System.Windows.Forms.Panel mainPanel; Control AutoScroll property set to TRUE messageLabel is initially blank private System.ComponentModel.Container components = null; // Visual Studio .NET-generated Dispose method [STAThread] static void Main() { Application.Run( new GroupBoxPanelExample() ); } 2007 Dr. Natheer Khasawneh 31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Outline // event handlers to change messageLabel // event handler for hi button private void hiButton_Click( object sender, System.EventArgs e ) { messageLabel.Text= "Hi pressed"; } // event handler for bye button private void byeButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Bye pressed"; } // event handler for far left button private void leftButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Far left pressed"; } GroupBoxPanelExa mple.cs hiButton and byeButton belong to GroupBox Represent event handlers Line messageLabel added to customize the text Panel has two buttons, leftButton and rightButton // event handler for far right button private void rightButton_Click( object sender, System.EventArgs e ) { messageLabel.Text = "Far right pressed"; } } // end class GroupBoxPanelExample 2007 Dr. Natheer Khasawneh 32 Outline GroupBoxPanelExa mple.cs Program Output hiButton_Click leftButton_Click rightButton_Click 2007 Dr. Natheer Khasawneh 33 13.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 2007 Dr. Natheer Khasawneh 34 13.7 CheckBoxes and RadioButtons CheckBox events and Description / Delegate and Event Arguments properties Common Properties Checked Whether or not the CheckBox has been checked. CheckState Whether the Checkbox is checked (contains a black checkmark) or unchecked (blank). An enumeration with values Checked, Unchecked or Indeterminate. Text Text displayed to the right of the CheckBox (called the label). Common Events (Delegate EventHandler, event arguments EventArgs) CheckedChanged Raised every time the Checkbox is either checked or unchecked. Default event when this control is double clicked in the designer. CheckStateChanged Raised when the CheckState property changes. Fig. 13.23 CheckBox properties and events. 2007 Dr. Natheer Khasawneh 35 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Outline // Fig. 13.24: CheckBoxTest.cs // Using CheckBoxes to toggle italic and bold styles. using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; /// form contains checkboxes to allow /// the user to modify sample text public class CheckBoxTest : System.Windows.Forms.Form { private System.Windows.Forms.CheckBox boldCheckBox; private System.Windows.Forms.CheckBox italicCheckBox; private System.Windows.Forms.Label outputLabel; CheckBoxTest.cs When program start, both Checkbox is unchecked Text property set to Bold The property Label OutputLabel Text set to Italic is labeled Watch the font style change private System.ComponentModel.Container components = null; // Visual Studio .NET-generated Dispose method /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new CheckBoxTest() ); } 2007 Dr. Natheer Khasawneh 36 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // 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 ); } Outline CheckBoxTest.cs Font constructor takes in the font name, size, and style Style is a member of the //Style make property text italic if not italic, Style object’s can useStyle bitwise property operators is FontStyle enumeration // if already Font italic make not italic itself is read-only set when object is created private void italicCheckBox_CheckedChanged( object sender, System.EventArgs e ) { outputLabel.Font = new Font( outputLabel.Font.Name, outputLabel.Font.Size, outputLabel.Font.Style ^ FontStyle.Italic ); } } // end class CheckBoxTest 2007 Dr. Natheer Khasawneh 37 Outline CheckBoxTest.cs Program Output Result when bold is selected Result when both styles are selected 2007 Dr. Natheer Khasawneh 38 13.7 CheckBoxes and RadioButtons RadioButton Description / Delegate and Event Arguments properties and events Common Properties Checked Whether the RadioButton is checked. Text Text displayed to the right of the RadioButton (called the label). Common Events (Delegate EventHandler, event arguments EventArgs) Click Raised when user clicks the control. CheckedChanged Raised every time the RadioButton is checked or unchecked. Default event when this control is double clicked in the designer. Fig. 13.25 RadioButton properties and events. 2007 Dr. Natheer Khasawneh 39 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Outline // Fig. 13.26: RadioButtonsTest.cs // Using RadioButtons to set message window options. using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; RadioButtonsTest .cs /// form contains several radio buttons--user chooses one /// from each group to create a custom MessageBox public class RadioButtonsTest : System.Windows.Forms.Form Label is used to prompt user { private System.Windows.Forms.Label promptLabel; Label is used to display private System.Windows.Forms.Label displayLabel; which button was pressed private System.Windows.Forms.Button displayButton; Display the text Display private System.Windows.Forms.RadioButton questionButton; private System.Windows.Forms.RadioButton informationButton; private System.Windows.Forms.RadioButton exclamationButton; RadioButtons are private System.Windows.Forms.RadioButton errorButton; private System.Windows.Forms.RadioButton retryCancelButton; created for the private System.Windows.Forms.RadioButton yesNoButton; enumeration options private System.Windows.Forms.RadioButton yesNoCancelButton; private System.Windows.Forms.RadioButton okCancelButton; One event handling exists for private System.Windows.Forms.RadioButton okButton; To store user’s choice of private System.Windows.Forms.RadioButton all the radio buttons in The enumeration options iconType is created. Object iconType is a abortRetryIgnoreButton; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox1; groupBox1 and groupBox2 name indicate which MessageBoxIcon button to display enumeration private MessageBoxIcon iconType = MessageBoxIcon.Error; 2007 Dr. Natheer Khasawneh 40 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 Outline private MessageBoxButtons buttonType = MessageBoxButtons.OK; The enumeration To storebuttonType user’s choice Object is of a name indicate options which buttonType is created MessageBoxButtom enumeration /// The main entry point for the application. button to display RadioButtonsTest [STAThread] .cs static void Main() Handlers compare the sender object { Application.Run( new RadioButtonsTest() ); button to determine with every radio } which button was selected // change button based on option chosen by sender private void buttonType_CheckedChanged( object sender, System.EventArgs e ) Each radio button generates { a CheckedChanged when if ( sender == okButton ) // display OK button clicked buttonType = MessageBoxButtons.OK; // display OK and Cancel buttons else if ( sender == okCancelButton ) buttonType = MessageBoxButtons.OKCancel; // display Abort, Retry and Ignore buttons else if ( sender == abortRetryIgnoreButton ) buttonType = MessageBoxButtons.AbortRetryIgnore; // display Yes, No and Cancel buttons else if ( sender == yesNoCancelButton ) buttonType = MessageBoxButtons.YesNoCancel; // display Yes and No buttons else if ( sender == yesNoButton ) buttonType = MessageBoxButtons.YesNo; // only one option left--display // Retry and Cancel buttons 2007 Dr. Natheer Khasawneh 41 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 Outline else buttonType = MessageBoxButtons.RetryCancel; Handlers compare the } // end method sender object with every radio button to determine buttonType_CheckedChanged which button was selected // 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; RadioButtonsTest .cs // display exclamation point else if ( sender == exclamationButton ) iconType = MessageBoxIcon.Exclamation; // display information icon else if ( sender == informationButton ) iconType = MessageBoxIcon.Information; else // only one option left--display question mark iconType = MessageBoxIcon.Question; } // end method iconType_CheckedChanged // display MessageBox and button user pressed protected void displayButton_Click( Result Click ofhandler messagefor box displayButton is a object sender, System.EventArgs e ) DialogResult creates a MessageBox enumeration { DialogResult result = Switch statement tests for the result and MessageBox.Show( "This is Your Custom MessageBox.", set displayLabel.Text appropriately "Custom MessageBox", buttonType, iconType, 0, 0 ); // check for dialog result and display it in label switch ( result ) 2007 Dr. Natheer Khasawneh 42 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 { case DialogResult.OK: displayLabel.Text = "OK was pressed."; break; case DialogResult.Cancel: displayLabel.Text = "Cancel was pressed."; break; case DialogResult.Abort: displayLabel.Text = "Abort was pressed."; break; case DialogResult.Retry: displayLabel.Text = "Retry was pressed."; break; Outline RadioButtonsTest .cs The result input will help determine which text to display among the cases case DialogResult.Ignore: displayLabel.Text = "Ignore was pressed."; break; case DialogResult.Yes: displayLabel.Text = "Yes was pressed."; break; case DialogResult.No: displayLabel.Text = "No was pressed."; break; } // end switch } // end method displayButton_Click } // end class RadioButtonsTest 2007 Dr. Natheer Khasawneh 43 Outline RadioButtonsTest .cs Program Output Radio button style allow user to select one per column Exclamation icon type OKCancel button type Error icon type OK button type 2007 Dr. Natheer Khasawneh 44 Outline Information icon type Question icon type AbortRetryIgnore button type YesNoCancel button type YesNo button type RadioButtonsTest .cs Program Output RetryCancel button type 2007 Dr. Natheer Khasawneh 45 13.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 2007 Dr. Natheer Khasawneh 46 13.8 PictureBoxes PictureBox Description / Delegate and Event Arguments properties and events 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. 13.27 PictureBox properties and events. 2007 Dr. Natheer Khasawneh 47 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline // Fig. 13.28: PictureBoxTest.cs // Using a PictureBox to display images. using using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; System.IO; /// form to display different images when clicked public class PictureBoxTest : System.Windows.Forms.Form { private System.Windows.Forms.PictureBox imagePictureBox; private System.Windows.Forms.Label promptLabel; PictureBoxTest.c s PictureBox imagePicture use to display one of three bitmap images private int imageNum = -1; /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new PictureBoxTest() ); Store the image we want to display } Includes instructions Click On Picture Box to View Images To respond to the Click // change image whenever PictureBox clicked Modulus calculation insures that private void imagePictureBox_Click( number is between 0 and 2 object sender, System.EventArgs e ) { imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2 event 2007 Dr. Natheer Khasawneh 48 33 34 35 36 37 38 39 // create Image object from file, display on PictureBox imagePictureBox.Image = Image.FromFile( Directory.GetCurrentDirectory() + "\\images\\image" + imageNum + ".bmp" ); } Method GetCurrentDirectory of Class Directory } //the end class PictureBoxTest Set Use Image imageNum property toofappend Method FromFile which returns current directory of file as a string imagePictureBox the correct number to an Image takes a string and creates an Image object Outline PictureBoxTest.c s Program Output 2007 Dr. Natheer Khasawneh 49 13.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 2007 Dr. Natheer Khasawneh 50 13.9 Mouse Event Handling M ouse Eve nts, Dele g a te s a nd Event Arg um e nts Mouse Events (Delegate EventHandler, event arguments EventArgs) MouseEnter Raised if the mouse cursor enters the area of the control. MouseLeave Raised if the mouse cursor leaves the area of the control. Mouse Events (Delegate MouseEventHandler, event arguments MouseEventArgs) MouseDown Raised if the mouse button is pressed while its cursor is over the area of the control. MouseHover Raised if the mouse cursor hovers over the area of the control. MouseMove Raised if the mouse cursor is moved while in the area of the control. MouseUp Raised if the mouse button is released when the cursor is over the area of the control. Class MouseEventArgs Properties Button Mouse button that was pressed (left, right, middle or none). Clicks The number of times the mouse button was clicked. X The x-coordinate of the event, relative to the component. Y The y-coordinate of the event, relative to the component. Fig. 12.29 Mo use e ve nts, d e le g a te s a nd e ve nt a rg um e nts. 2007 Dr. Natheer Khasawneh 51 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline // Fig 13.30: Painter.cs // Using the mouse to draw on a form. using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; /// creates a form as a drawing surface public class Painter : System.Windows.Forms.Form { bool shouldPaint = false; // whether to paint Painter.cs Creates variable shouldPaint to determine whether to draw on the form /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new Painter() ); } // should paint after mouse button has been pressed The event handler for private void Painter_MouseDown( MouseDown object sender, System.Windows.Forms.MouseEventArgs eevent ) { shouldPaint Mouse cursor willis set to true shouldPaint = true; } drawwhen this event occurs // stop painting when mouse button released The event handler of private void Painter_MouseUp( object sender, System.Windows.Forms.MouseEventArgs e )mouse shouldPaint set to false, event MouseUp { cursor will not draw shouldPaint = false; 2007 Dr. Natheer } Khasawneh 52 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 Outline // draw circle whenever mouse button // moves (and mouse is down) protected void Painter_MouseMove( Painter.cs object sender, System.Windows.Forms.MouseEventArgs e ) { Creates Program the graphic will draw only if if ( shouldPaint ) object shouldPaint for the formis true { FillEllipse draws a circle at every Graphics graphics = CreateGraphics(); Method Provides method for graphics.FillEllipse( new SolidBrush object point theCreate mouse cursor moves over and by drawing various shapes new SolidBrush( Color.BlueViolet ), passing the constructor a Color shouldPaint is true e.X, e.Y, 4, 4 ); value } } // end Coordinates of x and y and the pixels height Structure Color contain SolidBrush object determines andnumerous width are supplied to the parameter list Painter_MouseMove predefined color the constants color of the shape drawn } // end class Painter Program Output 2007 Dr. Natheer Khasawneh 53 Important Notes from MSDN • Mouse events occur in the following order: – – – – – MouseEnter MouseMove MouseHover / MouseDown / MouseWheel MouseUp MouseLeave 2007 Dr. Natheer Khasawneh 54 13.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 2007 Dr. Natheer Khasawneh 55 13.10 Keyboard Event Handling 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. 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. 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. Fig. 13.31 Keyboard events, delegates and event arguments. 2007 Dr. Natheer Khasawneh 56 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Outline // Fig. 13.32: KeyDemo.cs // Displaying information about the key the user pressed. using using using using using using System; System.Drawing; System.Collections; System.ComponentModel; System.Windows.Forms; System.Data; KeyDemo.cs // form to display key press // information--contains two labels public class KeyDemo : System.Windows.Forms.Form { private System.Windows.Forms.Label charLabel; private System.Windows.Forms.Label keyInfoLabel; Label for key pressed Forms contain Initially empty two Labels Label for modifier information private System.ComponentModel.Container components = null; /// The main entry point for the application. [STAThread] static void Main() { Application.Run( new KeyDemo() ); } KeyPress event Accesses the KeyChar property of If key pressed ishandler not ASCII, the KeyPressEventArgs object remains empty keycharLabel char // display the character pressed using protected void KeyDemo_KeyPress( object sender, System.Windows.Forms.KeyPressEventArgs e ) { Key pressed charLabel.Text = "Key pressed: " + e.KeyChar; } Display the key pressed as a char 2007 Dr. Natheer Khasawneh 57 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 Outline // display modifier keys, key code, key data and key value private void KeyDemo_KeyDown( object sender, System.Windows.Forms.KeyEventArgs e ) { KeyDemo.cs Uses Alt, Shift, and Control keyInfoLabel.Text = KeyEventArgs object "Alt: " + ( e.Alt ? "Yes" : properties "No") + '\n' + "Shift: " + ( e.Shift ? "Yes"KeyCode : "No" ) returns + '\n'the a+Keys key enumeration pressed This block test for special "Ctrl: " + ( e.Control ? "Yes"Displays : "No" ) + KeyCode, '\n' + the KeyData, and bool if matched KeyData property returns akeys, Keys converted without modifier into a string keys information using ToString return "KeyCode: " + e.KeyCode + '\n'KeyValue + properties enumeration with data about modifier keys "KeyData: " + e.KeyData + '\n' + "KeyValue: " + e.KeyValue; } KeyValue key code as ankey integer Integer valuereturns is the the Windows virtual code KeyUp event handler clears both labels // clear labels when key released private void KeyDemo_KeyUp( object sender, System.Windows.Forms.KeyEventArgs e ) { keyInfoLabel.Text = ""; charLabel.Text = ""; } 2007 Dr. Natheer Khasawneh 58 Outline Keys enumeration can test for specific keys by comparing key pressed to KeyCode KeyDemo.cs Program Output KeyDown event still raised so KeyPress eventdisplays was notinformation engaged keyInfoLabel 2007 Dr. Natheer Khasawneh 59 Important Notes From MSDN • Key events occur in the following order: – KeyDown – KeyPress – KeyUp • The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events. • Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes. • To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event-handling method to true. 2007 Dr. Natheer Khasawneh