Download presentation
Presentation is loading. Please wait.
Published byJohn Tate Modified over 9 years ago
1
2002 Prentice Hall. All rights reserved. 1 Week 7: GUI Questions from last lecture –Exception handling –Try-Catch blocks –Catching outside of scope Homework and Practical at end of slides
2
2002 Prentice Hall. All rights reserved. 2 Outline 12.1 Introduction 12.2 Windows Forms 12.3 Event-Handling Model 12.3.1 Basic Event Handling 12.4 Control Properties and Layout 12.5 Label s, TextBox es and Button s 12.6 GroupBox es and Panel s 12.7 CheckBox es and RadioButton s 12.8 PictureBox es 12.9 Mouse Event Handling 12.10 Keyboard Event Handling Chapter 12 - Graphical User Interface Concepts: Part 1
3
2002 Prentice Hall. All rights reserved. 3 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
4
2002 Prentice Hall. All rights reserved. 4 12.1 Introduction Fig. 12.1Sample Internet Explorer window with GUI components. ButtonLabelMenu Bar TextBoxScrollbar
5
2002 Prentice Hall. All rights reserved. 5 12.1 Introduction
6
2002 Prentice Hall. All rights reserved. 6 12.2 Windows Forms WinForms –Create GUIs for programs –Element on the desktop –Represented by: Dialog Window MDI window
7
2002 Prentice Hall. All rights reserved. 7 12.2 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
8
2002 Prentice Hall. All rights reserved. 8 12.2 Windows Forms Fig. 12.3Components and controls for Windows Forms.
9
2002 Prentice Hall. All rights reserved. 9 12.2 Windows Forms
10
2002 Prentice Hall. All rights reserved. 10 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
11
2002 Prentice Hall. All rights reserved. 11 12.3 Event-Handling Model Fig. 12.5Event-handling model using delegates. Object A raises event EDelegate for event E Handler 1 for event E Handler 3 for event E Handler 2 for event E calls
12
2002 Prentice Hall. All rights reserved. 12 12.3.1 Basic Event Handling 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
13
2002 Prentice Hall. All rights reserved. 13 12.3.1 Basic Event Handling Fig. 12.6Events section of the Properties window. Current even handler (none) Selected event Event description List of events supported by control Events icon
14
2002 Prentice Hall. All rights reserved. Outline 14 SimpleEventExamp le.cs 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 { 14 private System.ComponentModel.Container components = null; 15 16 // Visual Studio.NET generated code 17 18 [STAThread] 19 static void Main() 20 { 21 Application.Run( new MyForm() ); 22 } 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 } 30 31 } // end class MyForm Create an event handler Signature of the event handler Reference to the object that raised the event (sender) Reference to an event arguments object (e) Class EventArgs is base class for objects with event information
15
2002 Prentice Hall. All rights reserved. Outline 15 SimpleEventExamp le.cs Program Output
16
2002 Prentice Hall. All rights reserved. 16 12.3.1 Basic Event Handling Fig. 12.8List of Form events. Class name List of events
17
2002 Prentice Hall. All rights reserved. 17 12.3.1 Basic Event Handling Fig. 12.9Details of Click event. Event delegateEvent argument class Event name
18
2002 Prentice Hall. All rights reserved. 18 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
19
2002 Prentice Hall. All rights reserved. 19 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
20
2002 Prentice Hall. All rights reserved. 20 12.4 Control Properties and Layout
21
2002 Prentice Hall. All rights reserved. 21 12.4 Control Properties and Layout Fig. 12.11Anchoring demonstration. Constant distance to left and top sides Before resize After resize
22
2002 Prentice Hall. All rights reserved. 22 12.4 Control Properties and Layout Fig. 12.12Manipulating the Anchor property of a control. Darkened bar indicates to which wall control is anchored Click down-arrow in Anchor property to display anchoring window
23
2002 Prentice Hall. All rights reserved. 23 12.4 Control Properties and Layout Fig. 12.13Docking demonstration. Control expands along top portion of the form
24
2002 Prentice Hall. All rights reserved. 24 12.4 Control Properties and Layout
25
2002 Prentice Hall. All rights reserved. 25 12.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
26
2002 Prentice Hall. All rights reserved. 26 12.5 Labels, TextBoxes and Buttons Button –Control to trigger a specific action Checkboxes or radio buttons –Derived from ButtonBase
27
2002 Prentice Hall. All rights reserved. 27 12.5 Label s TextBox es and Button s
28
2002 Prentice Hall. All rights reserved. 28 12.5 Label s TextBox es and Button s
29
2002 Prentice Hall. All rights reserved. 29 12.5 Label s TextBox es and Button s
30
2002 Prentice Hall. All rights reserved. Outline 30 LabelTextBoxButt onTest.cs 1 // Fig. 12.18: LabelTextBoxButtonTest.cs 2 // Using a Textbox, Label and Button to display 3 // the hidden text in a password box. 4 5 using System; 6 using System.Drawing; 7 using System.Collections; 8 using System.ComponentModel; 9 using System.Windows.Forms; 10 using System.Data; 11 12 // namespace contains our form to display hidden text 13 namespace LabelTextBoxButtonTest 14 { 15 /// 16 /// form that creates a password textbox and 17 /// a label to display textbox contents 18 /// 19 public class LabelTextBoxButtonTest : 20 System.Windows.Forms.Form 21 { 22 private System.Windows.Forms.Button displayPasswordButton; 23 private System.Windows.Forms.Label displayPasswordLabel; 24 private System.Windows.Forms.TextBox inputPasswordTextBox; 25 26 /// 27 /// Required designer variable. 28 /// 29 private System.ComponentModel.Container components = null; 30 31 // default contructor 32 public LabelTextBoxButtonTest() 33 { 34 InitializeComponent(); 35 } Visual Studio.NET adds comments to our code Visual Studio.NET inserts declarations for the control we added to the form The IDE manages these declarationDeclare reference components (an array)Reference is nullConstructor for the form is created for usMethod InitializeComponent creates components and controls in the form and sets their properties
31
2002 Prentice Hall. All rights reserved. Outline 31 LabelTextBoxButt onTest.cs 36 37 /// 38 /// Clean up any resources being used. 39 /// 40 protected override void Dispose( bool disposing ) 41 { 42 if ( disposing ) 43 { 44 if ( components != null ) 45 { 46 components.Dispose(); 47 } 48 } 49 50 base.Dispose( disposing ); 51 } 52 53 #region Windows Form Designer generated code 54 /// 55 /// Required method for Designer support - do not modify 56 /// the contents of this method with the code editor. 57 /// 58 private void InitializeComponent() 59 { 60 this.displayPasswordButton = 61 new System.Windows.Forms.Button(); 62 this.inputPasswordTextBox = 63 new System.Windows.Forms.TextBox(); 64 this.displayPasswordLabel = 65 new System.Windows.Forms.Label(); 66 this.SuspendLayout(); 67 Method Dispose cleans up allocated resources #region preprocessor directives allow collapsible code in Visual Studio.NET Create new objects for the control we added
32
2002 Prentice Hall. All rights reserved. Outline 32 LabelTextBoxButt onTest.cs 68 // 69 // displayPasswordButton 70 // 71 this.displayPasswordButton.Location = 72 new System.Drawing.Point( 96, 96 ); 73 this.displayPasswordButton.Name = 74 "displayPasswordButton"; 75 this.displayPasswordButton.TabIndex = 1; 76 this.displayPasswordButton.Text = "Show Me"; 77 this.displayPasswordButton.Click += 78 new System.EventHandler( 79 this.displayPasswordButton_Click ); 80 81 // 82 // inputPasswordTextBox 83 // 84 this.inputPasswordTextBox.Location = 85 new System.Drawing.Point( 16, 16 ); 86 this.inputPasswordTextBox.Name = 87 "inputPasswordTextBox"; 88 this.inputPasswordTextBox.PasswordChar = '*'; 89 this.inputPasswordTextBox.Size = 90 new System.Drawing.Size( 264, 20 ); 91 this.inputPasswordTextBox.TabIndex = 0; 92 this.inputPasswordTextBox.Text = ""; 93 94 // 95 // displayPasswordLabel 96 // 97 this.displayPasswordLabel.BorderStyle = 98 System.Windows.Forms.BorderStyle.Fixed3D; 99 this.displayPasswordLabel.Location = 100 new System.Drawing.Point( 16, 48 ); 101 this.displayPasswordLabel.Name = 102 "displayPasswordLabel"; Set the Name, PasswordChar and Text properties for inputPasswordTextBox Visual Studio.NET register the event handler for us
33
2002 Prentice Hall. All rights reserved. Outline 33 LabelTextBoxButt onTest.cs 103 this.displayPasswordLabel.Size = 104 new System.Drawing.Size( 264, 23 ); 105 this.displayPasswordLabel.TabIndex = 2; 106 107 // 108 // LabelTextBoxButtonTest 109 // 110 this.AutoScaleBaseSize = 111 new System.Drawing.Size( 5, 13 ); 112 this.ClientSize = 113 new System.Drawing.Size( 292, 133 ); 114 this.Controls.AddRange( 115 new System.Windows.Forms.Control[] { 116 this.displayPasswordLabel, 117 this.inputPasswordTextBox, 118 this.displayPasswordButton}); 119 this.Name = "LabelTextBoxButtonTest"; 120 this.Text = "LabelTextBoxButtonTest"; 121 this.ResumeLayout( false ); 122 123 } // end method InitializeComponent 124 125 // end collapsible region started on line 53 126 #endregion 127 128 /// 129 /// The main entry point for the application. 130 /// 131 [STAThread] 132 static void Main() 133 { 134 Application.Run( new LabelTextBoxButtonTest() ); 135 } 136 #endregion signal the end of the collapsible region
34
2002 Prentice Hall. All rights reserved. Outline 34 LabelTextBoxButt onTest.cs Program Output 137 // display user input on label 138 protected void displayPasswordButton_Click( 139 object sender, System.EventArgs e ) 140 { 141 // text has not changed 142 displayPasswordLabel.Text = 143 inputPasswordTextBox.Text; 144 } 145 146 } // end class LabelTextBoxButtonTest 147 148 } // end namespace LabelTextBoxButtonTest Create an empty event handler named displayPasswordButton_Click To show the text, set displayPasswordLabel’s Text to inputPasswordTextBox’s Text User must program this line manually
35
2002 Prentice Hall. All rights reserved. 35 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
36
2002 Prentice Hall. All rights reserved. 36 12.6 GroupBox es and Panel s
37
2002 Prentice Hall. All rights reserved. 37 12.6 GroupBox es and Panel s
38
2002 Prentice Hall. All rights reserved. 38 12.6 GroupBox es and Panel s Fig. 12.21Creating a Panel with scrollbars. Controls inside panel panel panel scrollbars
39
2002 Prentice Hall. All rights reserved. Outline 39 GroupBoxPanelExa mple.cs 1 // Fig. 12.22: GroupBoxPanelExample.cs 2 // Using GroupBoxes and Panels to hold buttons. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 /// form to display a groupbox versus a panel 12 public class GroupBoxPanelExample : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Button hiButton; 15 private System.Windows.Forms.Button byeButton; 16 private System.Windows.Forms.Button leftButton; 17 private System.Windows.Forms.Button rightButton; 18 19 private System.Windows.Forms.GroupBox mainGroupBox; 20 private System.Windows.Forms.Label messageLabel; 21 private System.Windows.Forms.Panel mainPanel; 22 23 private System.ComponentModel.Container components = null; 24 25 // Visual Studio.NET-generated Dispose method 26 27 [STAThread] 28 static void Main() 29 { 30 Application.Run( new GroupBoxPanelExample() ); 31 } 32 messageLabel is initially blankGroupBox (name mainGroupBox)Panel (name mainPanel)Control AutoScroll property set to TRUE
40
2002 Prentice Hall. All rights reserved. Outline 40 GroupBoxPanelExa mple.cs 33 // event handlers to change messageLabel 34 35 // event handler for hi button 36 private void hiButton_Click( 37 object sender, System.EventArgs e ) 38 { 39 messageLabel.Text= "Hi pressed"; 40 } 41 42 // event handler for bye button 43 private void byeButton_Click( 44 object sender, System.EventArgs e ) 45 { 46 messageLabel.Text = "Bye pressed"; 47 } 48 49 // event handler for far left button 50 private void leftButton_Click( 51 object sender, System.EventArgs e ) 52 { 53 messageLabel.Text = "Far left pressed"; 54 } 55 56 // event handler for far right button 57 private void rightButton_Click( 58 object sender, System.EventArgs e ) 59 { 60 messageLabel.Text = "Far right pressed"; 61 } 62 63 } // end class GroupBoxPanelExample Represent event handlers hiButton and byeButton belong to GroupBox Panel has two buttons, leftButton and rightButton Line messageLabel added to customize the text
41
2002 Prentice Hall. All rights reserved. Outline 41 GroupBoxPanelExa mple.cs Program Output hiButton_Click leftButton_ClickrightButton_Click
42
2002 Prentice Hall. All rights reserved. 42 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
43
2002 Prentice Hall. All rights reserved. 43 12.7 CheckBox es and RadioButton s
44
2002 Prentice Hall. All rights reserved. Outline 44 CheckBoxTest.cs 1 // Fig. 12.24: 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 { 15 private System.Windows.Forms.CheckBox boldCheckBox; 16 private System.Windows.Forms.CheckBox italicCheckBox; 17 18 private System.Windows.Forms.Label outputLabel; 19 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 When program start, both Checkbox is unchecked Text property set to BoldText property set to ItalicThe Label OutputLabel is labeled Watch the font style change
45
2002 Prentice Hall. All rights reserved. Outline 45 CheckBoxTest.cs 31 // make text bold if not bold, 32 // if already bold make not bold 33 private void boldCheckBox_CheckedChanged( 34 object sender, System.EventArgs e ) 35 { 36 outputLabel.Font = 37 new Font( outputLabel.Font.Name, 38 outputLabel.Font.Size, 39 outputLabel.Font.Style ^ FontStyle.Bold ); 40 } 41 42 // make text italic if not italic, 43 // if already italic make not italic 44 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 Font constructor takes in the font name, size, and style Style is a member of the FontStyle enumeration Style property itself is read-only Font object’s Style property is set when object is created Style can use bitwise operators
46
2002 Prentice Hall. All rights reserved. Outline 46 CheckBoxTest.cs Program Output Result when bold is selectedResult when both styles are selected
47
2002 Prentice Hall. All rights reserved. 47 12.7 CheckBox es and RadioButton s
48
2002 Prentice Hall. All rights reserved. Outline 48 RadioButtonsTest.cs 1 // Fig. 12.26: 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 { 15 private System.Windows.Forms.Label promptLabel; 16 private System.Windows.Forms.Label displayLabel; 17 private System.Windows.Forms.Button displayButton; 18 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; 23 private System.Windows.Forms.RadioButton retryCancelButton; 24 private System.Windows.Forms.RadioButton yesNoButton; 25 private System.Windows.Forms.RadioButton yesNoCancelButton; 26 private System.Windows.Forms.RadioButton okCancelButton; 27 private System.Windows.Forms.RadioButton okButton; 28 private System.Windows.Forms.RadioButton 29 abortRetryIgnoreButton; 30 31 private System.Windows.Forms.GroupBox groupBox2; 32 private System.Windows.Forms.GroupBox groupBox1; 33 34 private MessageBoxIcon iconType = MessageBoxIcon.Error; To store user’s choice of options iconType is created. Object iconType is a MessageBoxIcon enumeration The enumeration name indicate which button to display Label is used to prompt userLabel is used to display which button was pressed Display the text DisplayRadioButtons are created for the enumeration options One event handling exists for all the radio buttons in groupBox1 and groupBox2
49
2002 Prentice Hall. All rights reserved. Outline 49 RadioButtonsTest.cs 35 private MessageBoxButtons buttonType = 36 MessageBoxButtons.OK; 37 38 /// The main entry point for the application. 39 [STAThread] 40 static void Main() 41 { 42 Application.Run( new RadioButtonsTest() ); 43 } 44 45 // change button based on option chosen by sender 46 private void buttonType_CheckedChanged( 47 object sender, System.EventArgs e ) 48 { 49 if ( sender == okButton ) // display OK button 50 buttonType = MessageBoxButtons.OK; 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 To store user’s choice of options buttonType is created Object buttonType is a MessageBoxButtom enumeration The enumeration name indicate which button to display Each radio button generates a CheckedChanged when clicked Handlers compare the sender object with every radio button to determine which button was selected
50
2002 Prentice Hall. All rights reserved. Outline 50 RadioButtonsTest.cs 70 else 71 buttonType = MessageBoxButtons.RetryCancel; 72 73 } // end method buttonType_CheckedChanged 74 75 // change icon based on option chosen by sender 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 ) 98 { 99 DialogResult result = 100 MessageBox.Show( "This is Your Custom MessageBox.", 101 "Custom MessageBox", buttonType, iconType, 0, 0 ); 102 103 // check for dialog result and display it in label 104 switch ( result ) Handlers compare the sender object with every radio button to determine which button was selected Click handler for displayButton creates a MessageBox Result of message box is a DialogResult enumeration Switch statement tests for the result and set displayLabel.Text appropriately
51
2002 Prentice Hall. All rights reserved. Outline 51 RadioButtonsTest.cs 105 { 106 case DialogResult.OK: 107 displayLabel.Text = "OK was pressed."; 108 break; 109 110 case DialogResult.Cancel: 111 displayLabel.Text = "Cancel was pressed."; 112 break; 113 114 case DialogResult.Abort: 115 displayLabel.Text = "Abort was pressed."; 116 break; 117 118 case DialogResult.Retry: 119 displayLabel.Text = "Retry was pressed."; 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 The result input will help determine which text to display among the cases
52
2002 Prentice Hall. All rights reserved. Outline 52 RadioButtonsTest.cs Program Output Exclamation icon type Error icon type OKCancel button type OK button type Radio button style allow user to select one per column
53
2002 Prentice Hall. All rights reserved. Outline 53 RadioButtonsTest.cs Program Output AbortRetryIgnore button type RetryCancel button type Information icon type Question icon type YesNoCancel button type YesNo button type
54
2002 Prentice Hall. All rights reserved. 54 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
55
2002 Prentice Hall. All rights reserved. 55 12.8 PictureBox es
56
2002 Prentice Hall. All rights reserved. Outline 56 PictureBoxTest.c s 1 // Fig. 12.28: PictureBoxTest.cs 2 // Using a PictureBox to display images. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.IO; 11 12 /// form to display different images when clicked 13 public class PictureBoxTest : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.PictureBox imagePictureBox; 16 private System.Windows.Forms.Label promptLabel; 17 18 private int imageNum = -1; 19 20 /// The main entry point for the application. 21 [STAThread] 22 static void Main() 23 { 24 Application.Run( new PictureBoxTest() ); 25 } 26 27 // change image whenever PictureBox clicked 28 private void imagePictureBox_Click( 29 object sender, System.EventArgs e ) 30 { 31 imageNum = ( imageNum + 1 ) % 3; // imageNum from 0 to 2 32 PictureBox imagePicture use to display one of three bitmap images Includes instructions Click On Picture Box to View Images To respond to the Click eventStore the image we want to displayModulus calculation insures that number is between 0 and 2
57
2002 Prentice Hall. All rights reserved. Outline 57 PictureBoxTest.c s Program Output 33 // create Image object from file, display on PictureBox 34 imagePictureBox.Image = Image.FromFile( 35 Directory.GetCurrentDirectory() + "\\images\\image" + 36 imageNum + ".bmp" ); 37 } 38 39 } // end class PictureBoxTest Set the Image property of imagePictureBox to an Image Method FromFile which takes a string and creates an Image object Method GetCurrentDirectory of Class Directory returns current directory of file as a string Use imageNum to append the correct number
58
2002 Prentice Hall. All rights reserved. 58 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
59
2002 Prentice Hall. All rights reserved. 59 12.9 Mouse Event Handling
60
2002 Prentice Hall. All rights reserved. Outline 60 Painter.cs 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 { 14 bool shouldPaint = false; // whether to paint 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( 25 object sender, System.Windows.Forms.MouseEventArgs e ) 26 { 27 shouldPaint = true; 28 } 29 30 // stop painting when mouse button released 31 private void Painter_MouseUp( 32 object sender, System.Windows.Forms.MouseEventArgs e ) 33 { 34 shouldPaint = false; 35 } 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
61
2002 Prentice Hall. All rights reserved. Outline 61 Painter.cs Program Output 36 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 ) 41 { 42 if ( shouldPaint ) 43 { 44 Graphics graphics = CreateGraphics(); 45 graphics.FillEllipse( 46 new SolidBrush( Color.BlueViolet ), 47 e.X, e.Y, 4, 4 ); 48 } 49 50 } // end Painter_MouseMove 51 52 } // end class Painter Program will draw only if shouldPaint is true Creates the graphic object for the form Provides method for drawing various shapes Method FillEllipse draws a circle at every point the mouse cursor moves over and shouldPaint is true SolidBrush object determines the color of the shape drawn Create new SolidBrush object by passing the constructor a Color value Structure Color contain numerous predefined color constants Coordinates of x and y and the pixels height and width are supplied to the parameter list
62
2002 Prentice Hall. All rights reserved. 62 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
63
2002 Prentice Hall. All rights reserved. 63 12.10 Keyboard Event Handling
64
2002 Prentice Hall. All rights reserved. Outline 64 KeyDemo.cs 1 // Fig. 12.32: KeyDemo.cs 2 // Displaying information about the key the user pressed. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // form to display key press 12 // information--contains two labels 13 public class KeyDemo : System.Windows.Forms.Form 14 { 15 private System.Windows.Forms.Label charLabel; 16 private System.Windows.Forms.Label keyInfoLabel; 17 18 private System.ComponentModel.Container components = null; 19 20 /// The main entry point for the application. 21 [STAThread] 22 static void Main() 23 { 24 Application.Run( new KeyDemo() ); 25 } 26 27 // display the character pressed using key char 28 protected void KeyDemo_KeyPress( 29 object sender, System.Windows.Forms.KeyPressEventArgs e ) 30 { 31 charLabel.Text = "Key pressed: " + e.KeyChar; 32 } 33 Forms contain two LabelsLabel for key pressedLabel for modifier informationInitially emptyKeyPress event handlerAccesses the KeyChar property of the KeyPressEventArgs object Key pressed as a char Display the key pressed If key pressed is not ASCII, charLabel remains empty
65
2002 Prentice Hall. All rights reserved. Outline 65 KeyDemo.cs 34 // display modifier keys, key code, key data and key value 35 private void KeyDemo_KeyDown( 36 object sender, System.Windows.Forms.KeyEventArgs e ) 37 { 38 keyInfoLabel.Text = 39 "Alt: " + ( e.Alt ? "Yes" : "No") + '\n' + 40 "Shift: " + ( e.Shift ? "Yes" : "No" ) + '\n' + 41 "Ctrl: " + ( e.Control ? "Yes" : "No" ) + '\n' + 42 "KeyCode: " + e.KeyCode + '\n' + 43 "KeyData: " + e.KeyData + '\n' + 44 "KeyValue: " + e.KeyValue; 45 } 46 47 // clear labels when key released 48 private void KeyDemo_KeyUp( 49 object sender, System.Windows.Forms.KeyEventArgs e ) 50 { 51 keyInfoLabel.Text = ""; 52 charLabel.Text = ""; 53 } KeyEventArgs object This block test for special keys, return bool if matched Uses Alt, Shift, and Control properties Displays the KeyCode, KeyData, and KeyValue properties KeyCode returns a Keys enumeration converted into a string using ToString KeyCode returns the key pressed without modifier keys information KeyData property returns a Keys enumeration with data about modifier keys KeyValue returns the key code as an integerInteger value is the Windows virtual key code KeyUp event handler clears both labels
66
2002 Prentice Hall. All rights reserved. Outline 66 KeyDemo.cs Program Output KeyPress event was not engagedKeyDown event still raised so keyInfoLabel displays information Keys enumeration can test for specific keys by comparing key pressed to KeyCode
67
2002 Prentice Hall. All rights reserved. 67 Chapter 13 – Graphical User Interfaces Part 2 Outline 13.1 Introduction 13.2 Menus 13.3 LinkLabels 13.4 ListBoxes and CheckedListBoxes 13.4.1 ListBoxes 13.4.2 CheckedListBoxes 13.5 ComboBoxes 13.6 TreeViews 13.7 ListViews 13.8 Tab Control 13.9 Multiple Document Interface (MDI) Windows 13.10Visual Inheritance 13.11 User-Defined Controls
68
2002 Prentice Hall. All rights reserved. 68 13.1 Introduction Continues study of Graphical User Interface Explores: –Menus –LinkLabels –ListBox –CheckedListBox –ComboBoxes –TreeView control –Tab controls –Multiple-document interface windows
69
2002 Prentice Hall. All rights reserved. 69 13.2 Menus Group related commands together Contain: –Commands –Submenus Exit uses Application class to quit Color options mutually exclusive Every option has its own event handler Font style options use Xor operator
70
2002 Prentice Hall. All rights reserved. 70 13.2 Menus Fig. 13.1Expanded and checked menus. Shortcut key Disabled command Separator bar Menu submenu Checked menu item
71
2002 Prentice Hall. All rights reserved. 71 13.2 Menus Fig. 13.2Visual Studio.NET Menu Designer. Text boxes used to add items to menu MainMenu icon Menu Designer Place & character before the letter to be underlined
72
2002 Prentice Hall. All rights reserved. 72 13.2 Menus
73
2002 Prentice Hall. All rights reserved. 73 13.2 Menus
74
2002 Prentice Hall. All rights reserved. Outline 74 MenuTest.cs 1 // Fig 13.4: MenuTest.cs 2 // Using menus to change font colors and 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 public class MenuTest : System.Windows.Forms.Form 12 { 13 // display label 14 private System.Windows.Forms.Label displayLabel; 15 16 // main menu (contains file and format menu) 17 private System.Windows.Forms.MainMenu mainMenu; 18 19 // file menu 20 private System.Windows.Forms.MenuItem fileMenuItem; 21 private System.Windows.Forms.MenuItem aboutMenuItem; 22 private System.Windows.Forms.MenuItem exitMenuItem; 23 24 // format menu 25 private System.Windows.Forms.MenuItem formatMenuItem; 26 27 // color submenu 28 private System.Windows.Forms.MenuItem colorMenuItem; 29 private System.Windows.Forms.MenuItem blackMenuItem; 30 private System.Windows.Forms.MenuItem blueMenuItem; 31 private System.Windows.Forms.MenuItem redMenuItem; 32 private System.Windows.Forms.MenuItem greenMenuItem; 33 About command Exit command Color options
75
2002 Prentice Hall. All rights reserved. Outline 75 MenuTest.cs 34 // font submenu 35 private System.Windows.Forms.MenuItem timesMenuItem; 36 private System.Windows.Forms.MenuItem courierMenuItem; 37 private System.Windows.Forms.MenuItem comicMenuItem; 38 private System.Windows.Forms.MenuItem boldMenuItem; 39 private System.Windows.Forms.MenuItem italicMenuItem; 40 private System.Windows.Forms.MenuItem fontMenuItem; 41 42 private System.Windows.Forms.MenuItem separatorMenuItem; 43 44 [STAThread] 45 static void Main() 46 { 47 Application.Run( new MenuTest() ); 48 } 49 50 // display MessageBox 51 private void aboutMenuItem_Click( 52 object sender, System.EventArgs e ) 53 { 54 MessageBox.Show( 55 "This is an example\nof using menus.", 56 "About", MessageBoxButtons.OK, 57 MessageBoxIcon.Information ); 58 } 59 60 // exit program 61 private void exitMenuItem_Click( 62 object sender, System.EventArgs e ) 63 { 64 Application.Exit(); 65 } 66 Font optionsStyle options About event handler Exit event Handler
76
2002 Prentice Hall. All rights reserved. Outline 76 MenuTest.cs 67 // reset color 68 private void ClearColor() 69 { 70 // clear all checkmarks 71 blackMenuItem.Checked = false; 72 blueMenuItem.Checked = false; 73 redMenuItem.Checked = false; 74 greenMenuItem.Checked = false; 75 } 76 77 // update menu state and color display black 78 private void blackMenuItem_Click( 79 object sender, System.EventArgs e ) 80 { 81 // reset checkmarks for color menu items 82 ClearColor(); 83 84 // set color to black 85 displayLabel.ForeColor = Color.Black; 86 blackMenuItem.Checked = true; 87 } 88 89 // update menu state and color display blue 90 private void blueMenuItem_Click( 91 object sender, System.EventArgs e ) 92 { 93 // reset checkmarks for color menu items 94 ClearColor(); 95 96 // set color to blue 97 displayLabel.ForeColor = Color.Blue; 98 blueMenuItem.Checked = true; 99 } 100 Black event handler Blue event Handler
77
2002 Prentice Hall. All rights reserved. Outline 77 MenuTest.cs 101 // update menu state and color display red 102 private void redMenuItem_Click( 103 object sender, System.EventArgs e ) 104 { 105 // reset checkmarks for color menu items 106 ClearColor(); 107 108 // set color to red 109 displayLabel.ForeColor = Color.Red; 110 redMenuItem.Checked = true; 111 } 112 113 // update menu state and color display green 114 private void greenMenuItem_Click( 115 object sender, System.EventArgs e ) 116 { 117 // reset checkmarks for color menu items 118 ClearColor(); 119 120 // set color to green 121 displayLabel.ForeColor = Color.Green; 122 greenMenuItem.Checked = true; 123 } 124 125 // reset font types 126 private void ClearFont() 127 { 128 // clear all checkmarks 129 timesMenuItem.Checked = false; 130 courierMenuItem.Checked = false; 131 comicMenuItem.Checked = false; 132 } 133 Red event handler Green event handler
78
2002 Prentice Hall. All rights reserved. Outline 78 MenuTest.cs 134 // update menu state and set font to Times 135 private void timesMenuItem_Click( 136 object sender, System.EventArgs e ) 137 { 138 // reset checkmarks for font menu items 139 ClearFont(); 140 141 // set Times New Roman font 142 timesMenuItem.Checked = true; 143 displayLabel.Font = new Font( 144 "Times New Roman", 14, displayLabel.Font.Style ); 145 } 146 147 // update menu state and set font to Courier 148 private void courierMenuItem_Click( 149 object sender, System.EventArgs e ) 150 { 151 // reset checkmarks for font menu items 152 ClearFont(); 153 154 // set Courier font 155 courierMenuItem.Checked = true; 156 displayLabel.Font = new Font( 157 "Courier New", 14, displayLabel.Font.Style ); 158 } 159 160 // update menu state and set font to Comic Sans MS 161 private void comicMenuItem_Click( 162 object sender, System.EventArgs e ) 163 { 164 // reset checkmarks for font menu items 165 ClearFont(); 166 Times New Roman event handler Courier New event handler Comic Sans event handler
79
2002 Prentice Hall. All rights reserved. Outline 79 MenuTest.cs 167 // set Comic Sans font 168 comicMenuItem.Checked = true; 169 displayLabel.Font = new Font( 170 "Comic Sans MS", 14, displayLabel.Font.Style ); 171 } 172 173 // toggle checkmark and toggle bold style 174 private void boldMenuItem_Click( 175 object sender, System.EventArgs e ) 176 { 177 // toggle checkmark 178 boldMenuItem.Checked = !boldMenuItem.Checked; 179 180 // use Xor to toggle bold, keep all other styles 181 displayLabel.Font = new Font( 182 displayLabel.Font.FontFamily, 14, 183 displayLabel.Font.Style ^ FontStyle.Bold ); 184 } 185 186 // toggle checkmark and toggle italic style 187 private void italicMenuItem_Click( 188 object sender, System.EventArgs e) 189 { 190 // toggle checkmark 191 italicMenuItem.Checked = !italicMenuItem.Checked; 192 193 // use Xor to toggle bold, keep all other styles 194 displayLabel.Font = new Font( 195 displayLabel.Font.FontFamily, 14, 196 displayLabel.Font.Style ^ FontStyle.Italic ); 197 } 198 199 } // end class MenuTest Bold event handler Italic event handler
80
2002 Prentice Hall. All rights reserved. Outline 80 MenuTest.cs Program Output
81
2002 Prentice Hall. All rights reserved. 81 13.3 LinkLabel s Displays links to other objects –Uses event handlers to link to right file or program –Start method of Process class opens other programs Derived from class Label, inherits functionality
82
2002 Prentice Hall. All rights reserved. 82 13.3 LinkLabel s Fig. 13.5 LinkLabel control in the design phase and in running program. LinkLabel on a form Hand image displayed when mouse cursor over a LinkLabel
83
2002 Prentice Hall. All rights reserved. 83 13.3 LinkLabel s
84
2002 Prentice Hall. All rights reserved. Outline 84 LinkLabelTest.cs 1 // Fig. 13.7: LinkLabelTest.cs 2 // Using LinkLabels to create hyperlinks. 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 public class LinkLabelTest : System.Windows.Forms.Form 12 { 13 // linklabels to C: drive, www.deitel.com and Notepad 14 private System.Windows.Forms.LinkLabel driveLinkLabel; 15 private System.Windows.Forms.LinkLabel deitelLinkLabel; 16 private System.Windows.Forms.LinkLabel notepadLinkLabel; 17 18 [STAThread] 19 static void Main() 20 { 21 Application.Run( new LinkLabelTest() ); 22 } 23 24 // browse C:\ drive 25 private void driveLinkLabel_LinkClicked( object sender, 26 System.Windows.Forms.LinkLabelLinkClickedEventArgs e ) 27 { 28 driveLinkLabel.LinkVisited = true; 29 System.Diagnostics.Process.Start( "C:\\" ); 30 } 31 C drive linkNotepad linkDeitel website link C drive event handler Start method to open other programs
85
2002 Prentice Hall. All rights reserved. Outline 85 LinkLabelTest.cs 32 // load www.deitel.com in Web broswer 33 private void deitelLinkLabel_LinkClicked( object sender, 34 System.Windows.Forms.LinkLabelLinkClickedEventArgs e ) 35 { 36 deitelLinkLabel.LinkVisited = true; 37 System.Diagnostics.Process.Start( 38 "IExplore", "http://www.deitel.com" ); 39 } 40 41 // run application Notepad 42 private void notepadLinkLabel_LinkClicked( 43 object sender, 44 System.Windows.Forms.LinkLabelLinkClickedEventArgs e ) 45 { 46 notepadLinkLabel.LinkVisited = true; 47 48 // program called as if in run 49 // menu and full path not needed 50 System.Diagnostics.Process.Start( "notepad" ); 51 } 52 53 } // end class LinkLabelTest Deitel website event handler Notepad event handler
86
2002 Prentice Hall. All rights reserved. Outline 86 LinkLabelTest.cs Program Output Click on first LinkLabel to look at contents of C drive
87
2002 Prentice Hall. All rights reserved. Outline 87 LinkLabelTest.cs Program Output Click on second LinkLabel to go to the Web Site
88
2002 Prentice Hall. All rights reserved. Outline 88 LinkLabelTest.cs Program Output Click the third LinkLabel to open notepad
89
2002 Prentice Hall. All rights reserved. 89 13.4 ListBox es and CheckedListBox es ListBoxe s –Allow users to view and select from items on a list –Static objects –SelectionMode property determines number of items that can be selected –Property Items returns all objects in list –Property SelectedItem returns current selected item –Property SelectedIndex returns index of selected item –Property GetSelected returns true if property at given index is selected –Use Add method to add to Items collection myListBox. Items.Add (“myListItem”)
90
2002 Prentice Hall. All rights reserved. 90 13.4 ListBox es and CheckedListBox es CheckedListBoxe s –Extends ListBox by placing check boxes next to items –Can select more than one object at one time
91
2002 Prentice Hall. All rights reserved. 91 13.4.1 ListBox es Class ListBoxTest –Allows users to add and remove items from ListBox –Uses event handlers to add to, remove from and clear list
92
2002 Prentice Hall. All rights reserved. 92 13.4.2 CheckedListBox es CheckedListBox derives from class ListBox –Can add to, remove from or clear list –Can select multiple items from the list –Properties CurrentValue and NewValue return state of object selected –Properties CheckedItems and CheckedIndices return the objects and indices of selected items respectively
93
2002 Prentice Hall. All rights reserved. 93 13.4 ListBox es and CheckListBox es Fig. 13.8 ListBox and CheckedListBox on a form. ListBox Selected Items Checked item CheckedListBox Scroll bars appear if necessary
94
2002 Prentice Hall. All rights reserved. 94 13.4 ListBox es and CheckListBox es
95
2002 Prentice Hall. All rights reserved. 95 13.4 ListBox es and CheckListBox es Fig. 13.10 String Collection Editor.
96
2002 Prentice Hall. All rights reserved. Outline 96 ListBoxTest.cs 1 // Fig 13.11: ListBoxTest.cs 2 // Program to add, remove and clear list box items. 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 public class ListBoxTest : System.Windows.Forms.Form 12 { 13 // contains user-input list of elements 14 private System.Windows.Forms.ListBox displayListBox; 15 16 // user input textbox 17 private System.Windows.Forms.TextBox inputTextBox; 18 19 // add, remove, clear and exit command buttons 20 private System.Windows.Forms.Button addButton; 21 private System.Windows.Forms.Button removeButton; 22 private System.Windows.Forms.Button clearButton; 23 private System.Windows.Forms.Button exitButton; 24 25 [STAThread] 26 static void Main() 27 { 28 Application.Run( new ListBoxTest() ); 29 } 30 Display ListBoxText field for inputAdd button Remove Button Clear button Exit button
97
2002 Prentice Hall. All rights reserved. Outline 97 ListBoxTest.cs 31 // add new item (text from input box) 32 // and clear input box 33 private void addButton_Click( 34 object sender, System.EventArgs e ) 35 { 36 displayListBox.Items.Add( inputTextBox.Text ); 37 inputTextBox.Clear(); 38 } 39 40 // remove item if one selected 41 private void removeButton_Click( 42 object sender, System.EventArgs e ) 43 { 44 // remove only if item selected 45 if ( displayListBox.SelectedIndex != -1 ) 46 displayListBox.Items.RemoveAt( 47 displayListBox.SelectedIndex ); 48 } 49 50 // clear all items 51 private void clearButton_Click( 52 object sender, System.EventArgs e ) 53 { 54 displayListBox.Items.Clear(); 55 } 56 57 // exit application 58 private void exitButton_Click( 59 object sender, System.EventArgs e ) 60 { 61 Application.Exit(); 62 } 63 64 } // end class ListBoxTest Add event handler Add method Remove methodClear methodTest if item is selected Exit
98
2002 Prentice Hall. All rights reserved. Outline 98 ListBoxTest.cs Program Output
99
2002 Prentice Hall. All rights reserved. 99 13.4 ListBox es and CheckListBox es
100
2002 Prentice Hall. All rights reserved. Outline 100 CheckedListBoxTe st.cs 1 // Fig. 13.13: CheckedListBoxTest.cs 2 // Using the checked list boxes to add items to a list box 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 public class CheckedListBoxTest : System.Windows.Forms.Form 12 { 13 // list of available book titles 14 private System.Windows.Forms.CheckedListBox 15 inputCheckedListBox; 16 17 // user selection list 18 private System.Windows.Forms.ListBox displayListBox; 19 20 [STAThread] 21 static void Main() 22 { 23 Application.Run( new CheckedListBoxTest() ); 24 } 25 26 // item about to change, 27 // add or remove from displayListBox 28 private void inputCheckedListBox_ItemCheck( 29 object sender, 30 System.Windows.Forms.ItemCheckEventArgs e ) 31 { 32 // obtain reference of selected item 33 string item = 34 inputCheckedListBox.SelectedItem.ToString(); 35 CheckedListBoxListBoxItemCheck event handler
101
2002 Prentice Hall. All rights reserved. Outline 101 CheckedListBoxTe st.cs Program Output 36 // if item checked add to listbox 37 // otherwise remove from listbox 38 if ( e.NewValue == CheckState.Checked ) 39 displayListBox.Items.Add( item ); 40 else 41 displayListBox.Items.Remove( item ); 42 43 } // end method inputCheckedListBox_Click 44 45 } // end class CheckedListBox Add ItemRemove Item
102
2002 Prentice Hall. All rights reserved. 102 13.5 ComboBox es Combine TextBox and drop-down list Add method adds object to collection Properties: – DropDownStyle: determines type of ComboBox –Items: returns objects in the list –SelectedItem : returns object selected –SelectedIndex : returns index of selected item
103
2002 Prentice Hall. All rights reserved. 103 13.5 ComboBox es Fig. 13.14Demonstrating a ComboBox.
104
2002 Prentice Hall. All rights reserved. 104 13.5 ComboBox es
105
2002 Prentice Hall. All rights reserved. Outline 105 ComboBoxTest.cs 1 // Fig. 13.16: ComboBoxTest.cs 2 // Using ComboBox to select shape to draw 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 public class ComboBoxTest : System.Windows.Forms.Form 12 { 13 // contains shape list (circle, square, ellipse, pie) 14 private System.Windows.Forms.ComboBox imageComboBox; 15 16 [STAThread] 17 static void Main() 18 { 19 Application.Run( new ComboBoxTest() ); 20 } 21 22 // get selected index, draw shape 23 private void imageComboBox_SelectedIndexChanged( 24 object sender, System.EventArgs e ) 25 { 26 // create graphics object, pen and brush 27 Graphics myGraphics = base.CreateGraphics(); 28 29 // create Pen using color DarkRed 30 Pen myPen = new Pen( Color.DarkRed ); 31 32 // create SolidBrush using color DarkRed 33 SolidBrush mySolidBrush = 34 new SolidBrush( Color.DarkRed ); 35 Create ComboBoxSelectedIndexChanged event handler Create graphics objectCreate penCreate brush
106
2002 Prentice Hall. All rights reserved. Outline 106 ComboBoxTest.cs 36 // clear drawing area setting it to color White 37 myGraphics.Clear( Color.White ); 38 39 // find index, draw proper shape 40 switch ( imageComboBox.SelectedIndex ) 41 { 42 case 0: // case circle is selected 43 myGraphics.DrawEllipse( 44 myPen, 50, 50, 150, 150 ); 45 break; 46 case 1: // case rectangle is selected 47 myGraphics.DrawRectangle( 48 myPen, 50, 50, 150, 150 ); 49 break; 50 case 2: // case ellipse is selected 51 myGraphics.DrawEllipse( 52 myPen, 50, 85, 150, 115 ); 53 break; 54 case 3: // case pie is selected 55 myGraphics.DrawPie( 56 myPen, 50, 50, 150, 150, 0, 45 ); 57 break; 58 case 4: // case filled circle is selected 59 myGraphics.FillEllipse( 60 mySolidBrush, 50, 50, 150, 150 ); 61 break; 62 case 5: // case filled rectangle is selected 63 myGraphics.FillRectangle( 64 mySolidBrush, 50, 50, 150, 150 ); 65 break; 66 case 6: // case filled ellipse is selected 67 myGraphics.FillEllipse( 68 mySolidBrush, 50, 85, 150, 115 ); 69 break; Switch statement to determine correct object to draw Draw object
107
2002 Prentice Hall. All rights reserved. Outline 107 ComboBoxTest.cs Program Output 70 case 7: // case filled pie is selected 71 myGraphics.FillPie( 72 mySolidBrush, 50, 50, 150, 150, 0, 45 ); 73 break; 74 75 } // end switch 76 77 } // end method imageComboBox_SelectedIndexChanged 78 79 } // end class ComboBoxTest
108
2002 Prentice Hall. All rights reserved. Outline 108 ComboBoxTest.cs Program Output
109
2002 Prentice Hall. All rights reserved. 109 13.6 TreeView s Displays nodes hierarchically Parent nodes have children The first parent node is called the root Use Add method to add nodes
110
2002 Prentice Hall. All rights reserved. 110 13.6 TreeView Fig. 13.17Displaying a sample tree in a TreeView. Click to expand node, displaying child nodes Root node Child nodes Click to collapse node, hiding child nodes
111
2002 Prentice Hall. All rights reserved. 111 13.6 TreeView
112
2002 Prentice Hall. All rights reserved. 112 13.6 TreeView
113
2002 Prentice Hall. All rights reserved. 113 13.6 TreeView Fig. 13.20 TreeNode Editor.
114
2002 Prentice Hall. All rights reserved. Outline 114 TreeViewDirector yStructureTest.c s 1 // Fig. 13.21: TreeViewDirectoryStructureTest.cs 2 // Using TreeView to display directory structure 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 public class TreeViewDirectoryStructureTest 13 : System.Windows.Forms.Form 14 { 15 // contains view of c: drive directory structure 16 private System.Windows.Forms.TreeView directoryTreeView; 17 18 [STAThread] 19 static void Main() 20 { 21 Application.Run( 22 new TreeViewDirectoryStructureTest() ); 23 } 24 25 public void PopulateTreeView( 26 string directoryValue, TreeNode parentNode ) 27 { 28 // populate current node with subdirectories 29 string[] directoryArray = 30 Directory.GetDirectories( directoryValue ); 31 Class that creates children of root Get subdirectories of root
115
2002 Prentice Hall. All rights reserved. Outline 115 TreeViewDirector yStructureTest.c s 32 // populate current node with subdirectories 33 try 34 { 35 if ( directoryArray.Length != 0 ) 36 { 37 // for every subdirectory, create new TreeNode, 38 // add as child of current node and recursively 39 // populate child nodes with subdirectories 40 foreach ( string directory in directoryArray ) 41 { 42 // create TreeNode for current directory 43 TreeNode myNode = new TreeNode( directory ); 44 45 // add current directory node to parent node 46 parentNode.Nodes.Add( myNode ); 47 48 // recursively populate every subdirectory 49 PopulateTreeView( directory, myNode ); 50 } 51 52 } // end if 53 } 54 55 // catch exception 56 catch ( UnauthorizedAccessException ) 57 { 58 parentNode.Nodes.Add( "Access denied" ); 59 } 60 61 } // end PopulateTreeView 62 Catches security exception Create new nodeRecursive call to finish tree
116
2002 Prentice Hall. All rights reserved. Outline 116 TreeViewDirector yStructureTest.c s 63 // called by system when form loads 64 private void TreeViewDirectoryStructureTest_Load( 65 object sender, System.EventArgs e) 66 { 67 // add c:\ drive to directoryTreeView and 68 // insert its subfolders 69 directoryTreeView.Nodes.Add( "C:\\" ); 70 PopulateTreeView( 71 "C:\\", directoryTreeView.Nodes[ 0 ] ); 72 } 73 74 } // end class TreeViewDirectoryStructure Create root
117
2002 Prentice Hall. All rights reserved. Outline 117 TreeViewDirector yStructureTest.c s Program Output
118
2002 Prentice Hall. All rights reserved. 118 13.7 ListView s Displays list of items –Can select one or more items from list –Displays icons to go along with items
119
2002 Prentice Hall. All rights reserved. 119 13.7 ListView s
120
2002 Prentice Hall. All rights reserved. 120 13.7 ListView s Fig. 13.23 Image Collection Editor window for an ImageList component.
121
2002 Prentice Hall. All rights reserved. Outline 121 ListViewTest.cs 1 // Fig. 13.24: ListViewTest.cs 2 // Displaying directories and their contents in ListView. 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 public class ListViewTest : System.Windows.Forms.Form 13 { 14 // display labels for current location 15 // in directory tree 16 private System.Windows.Forms.Label currentLabel; 17 private System.Windows.Forms.Label displayLabel; 18 19 // display contents of current directory 20 private System.Windows.Forms.ListView browserListView; 21 22 // specifies images for file icons and folder icons 23 private System.Windows.Forms.ImageList fileFolder; 24 25 // get current directory 26 string currentDirectory = 27 Directory.GetCurrentDirectory(); 28 29 [STAThread] 30 static void Main() 31 { 32 Application.Run( new ListViewTest() ); 33 } 34 Create Image ListLoad the current directory
122
2002 Prentice Hall. All rights reserved. Outline 122 ListViewTest.cs 35 // browse directory user clicked or go up one level 36 private void browserListView_Click( 37 object sender, System.EventArgs e ) 38 { 39 // ensure item selected 40 if ( browserListView.SelectedItems.Count != 0 ) 41 { 42 // if first item selected, go up one level 43 if ( browserListView.Items[ 0 ].Selected ) 44 { 45 // create DirectoryInfo object for directory 46 DirectoryInfo directoryObject = 47 new DirectoryInfo( currentDirectory ); 48 49 // if directory has parent, load it 50 if ( directoryObject.Parent != null ) 51 LoadFilesInDirectory( 52 directoryObject.Parent.FullName ); 53 } 54 55 // selected directory or file 56 else 57 { 58 // directory or file chosen 59 string chosen = 60 browserListView.SelectedItems[ 0 ].Text; 61 62 // if item selected is directory 63 if ( Directory.Exists( currentDirectory + 64 "\\" + chosen ) ) 65 { Test to see if at rootReturn parent of current directory Check if selected item is directory Test if item is selected If first item selected go up one level Make directory information
123
2002 Prentice Hall. All rights reserved. Outline 123 ListViewTest.cs 66 // load subdirectory 67 // if in c:\, do not need '\', 68 // otherwise we do 69 if ( currentDirectory == "C:\\" ) 70 LoadFilesInDirectory( 71 currentDirectory + chosen ); 72 else 73 LoadFilesInDirectory( 74 currentDirectory + "\\" + chosen ); 75 } //end if 76 77 } // end else 78 79 // update displayLabel 80 displayLabel.Text = currentDirectory; 81 82 } // end if 83 84 } // end method browserListView_Click 85 86 // display files/subdirectories of current directory 87 public void LoadFilesInDirectory( 88 string currentDirectoryValue ) 89 { 90 // load directory information and display 91 try 92 { 93 // clear ListView and set first item 94 browserListView.Items.Clear(); 95 browserListView.Items.Add( "Go Up One Level" ); 96 Class to load files in current directory Update to display current directory Load subdirectory
124
2002 Prentice Hall. All rights reserved. Outline 124 ListViewTest.cs 97 // update current directory 98 currentDirectory = currentDirectoryValue; 99 DirectoryInfo newCurrentDirectory = 100 new DirectoryInfo( currentDirectory ); 101 102 // put files and directories into arrays 103 DirectoryInfo[] directoryArray = 104 newCurrentDirectory.GetDirectories(); 105 106 FileInfo[] fileArray = 107 newCurrentDirectory.GetFiles(); 108 109 // add directory names to ListView 110 foreach ( DirectoryInfo dir in directoryArray ) 111 { 112 // add directory to ListView 113 ListViewItem newDirectoryItem = 114 browserListView.Items.Add( dir.Name ); 115 116 // set directory image 117 newDirectoryItem.ImageIndex = 0; 118 } 119 120 // add file names to ListView 121 foreach ( FileInfo file in fileArray ) 122 { 123 // add file to ListView 124 ListViewItem newFileItem = 125 browserListView.Items.Add( file.Name ); 126 127 newFileItem.ImageIndex = 1; // set file image 128 } 129 } // end try 130 Get subdirectories of current directory Get files of current directory Add directory to list Add file to list
125
2002 Prentice Hall. All rights reserved. Outline 125 ListViewTest.cs 131 // access denied 132 catch ( UnauthorizedAccessException exception ) 133 { 134 MessageBox.Show( 135 "Warning: Some fields may not be " + 136 "visible due to permission settings", 137 "Attention", 0, MessageBoxIcon.Warning ); 138 } 139 140 } // end method LoadFilesInDirectory 141 142 // handle load event when Form displayed for first time 143 private void ListViewTest_Load( 144 object sender, System.EventArgs e ) 145 { 146 // set image list 147 Image folderImage = Image.FromFile( 148 currentDirectory + "\\images\\folder.bmp" ); 149 150 Image fileImage = Image.FromFile( currentDirectory + 151 "\\images\\file.bmp" ); 152 153 fileFolder.Images.Add( folderImage ); 154 fileFolder.Images.Add( fileImage ); 155 156 // load current directory into browserListView 157 LoadFilesInDirectory( currentDirectory ); 158 displayLabel.Text = currentDirectory; 159 160 } // end method ListViewTest_Load 161 162 } // end class ListViewTest Security exception handler Load Images
126
2002 Prentice Hall. All rights reserved. Outline 126 ListViewTest.cs Program Output
127
2002 Prentice Hall. All rights reserved. 127 13.8 TabControl Creates tabbed windows Windows called TabPage objects –TabPages can have controls –Tabpages have own Click event for when tab is clicked
128
2002 Prentice Hall. All rights reserved. 128 13.8 Tab Control s Fig. 13.25Tabbed pages in Visual Studio.NET. Tab pages
129
2002 Prentice Hall. All rights reserved. 129 13.8 Tab Control s Fig. 13.26Example TabControl with TabPage s. TabPage TabControl Controls in TabPage
130
2002 Prentice Hall. All rights reserved. 130 13.8 Tab Control s Fig. 13.27Adding TabPage s to the TabControl.
131
2002 Prentice Hall. All rights reserved. 131 13.8 Tab Control s
132
2002 Prentice Hall. All rights reserved. Outline 132 UsingTabs.cs 1 // Fig. 13.29: UsingTabs.cs 2 // Using TabControl to display various font settings. 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 public class UsingTabs : System.Windows.Forms.Form 12 { 13 // output label reflects text changes 14 private System.Windows.Forms.Label displayLabel; 15 16 // table control containing table pages colorTabPage, 17 // sizeTabPage, messageTabPage and aboutTabPage 18 private System.Windows.Forms.TabControl 19 optionsTabControl; 20 21 // table page containing color options 22 private System.Windows.Forms.TabPage colorTabPage; 23 private System.Windows.Forms.RadioButton 24 greenRadioButton; 25 private System.Windows.Forms.RadioButton redRadioButton; 26 private System.Windows.Forms.RadioButton 27 blackRadioButton; 28 Color tab Color buttons for color tab
133
2002 Prentice Hall. All rights reserved. Outline 133 UsingTabs.cs 29 // table page containing font size options 30 private System.Windows.Forms.TabPage sizeTabPage; 31 private System.Windows.Forms.RadioButton 32 size20RadioButton; 33 private System.Windows.Forms.RadioButton 34 size16RadioButton; 35 private System.Windows.Forms.RadioButton 36 size12RadioButton; 37 38 // table page containing text display options 39 private System.Windows.Forms.TabPage messageTabPage; 40 private System.Windows.Forms.RadioButton 41 goodByeRadioButton; 42 private System.Windows.Forms.RadioButton 43 helloRadioButton; 44 45 // table page containing about message 46 private System.Windows.Forms.TabPage aboutTabPage; 47 private System.Windows.Forms.Label messageLabel; 48 49 [STAThread] 50 static void Main() 51 { 52 Application.Run( new UsingTabs() ); 53 } 54 55 // event handler for black color radio button 56 private void blackRadioButton_CheckedChanged( 57 object sender, System.EventArgs e ) 58 { 59 displayLabel.ForeColor = Color.Black; 60 } 61 Size tab Size buttons Message tabAbout tabEvent handler
134
2002 Prentice Hall. All rights reserved. Outline 134 UsingTabs.cs 62 // event handler for red color radio button 63 private void redRadioButton_CheckedChanged( 64 object sender, System.EventArgs e ) 65 { 66 displayLabel.ForeColor = Color.Red; 67 } 68 69 // event handler for green color radio button 70 private void greenRadioButton_CheckedChanged( 71 object sender, System.EventArgs e ) 72 { 73 displayLabel.ForeColor = Color.Green; 74 } 75 76 // event handler for size 12 radio button 77 private void size12RadioButton_CheckedChanged( 78 object sender, System.EventArgs e ) 79 { 80 displayLabel.Font = 81 new Font( displayLabel.Font.Name, 12 ); 82 } 83 84 // event handler for size 16 radio button 85 private void size16RadioButton_CheckedChanged( 86 object sender, System.EventArgs e ) 87 { 88 displayLabel.Font = 89 new Font( displayLabel.Font.Name, 16 ); 90 } 91 Event handlers
135
2002 Prentice Hall. All rights reserved. Outline 135 UsingTabs.cs 92 // event handler for size 20 radio button 93 private void size20RadioButton_CheckedChanged( 94 object sender, System.EventArgs e ) 95 { 96 displayLabel.Font = 97 new Font( displayLabel.Font.Name, 20 ); 98 } 99 100 // event handler for message "Hello!" radio button 101 private void helloRadioButton_CheckedChanged( 102 object sender, System.EventArgs e ) 103 { 104 displayLabel.Text = "Hello!"; 105 } 106 107 // event handler for message "Goodbye!" radio button 108 private void goodByeRadioButton_CheckedChanged( 109 object sender, System.EventArgs e ) 110 { 111 displayLabel.Text = "Goodbye!"; 112 } 113 114 } // end class UsingTabs Event handlers
136
2002 Prentice Hall. All rights reserved. Outline 136 UsingTabs.cs Program Output
137
2002 Prentice Hall. All rights reserved. 137 13.9 Multiple-Document Interface Windows Users can edit multiple documents at once Usually more complex then single-document- interface applications Application window called parent, others child Parent and child menus can be merged –Based on MergeOrder property Child windows can be arranged in parent window: –Tiled windows: completely fill parent, no overlap Either horizontal or vertical –Cascaded windows: overlap, same size, display title bar –ArrangeIcons: arranges icons for minimized windows
138
2002 Prentice Hall. All rights reserved. 138 13.9 Multiple Document Interface (MDI) Windows Fig. 13.30MDI parent and MDI child. MDI parent MDI child
139
2002 Prentice Hall. All rights reserved. 139 13.9 Multiple Document Interface (MDI) Windows Fig. 13.31SDI and MDI forms. Single Document Interface (SDI)Multiple Document Interface (MDI)
140
2002 Prentice Hall. All rights reserved. 140 13.9 Multiple Document Interface (MDI) Windows
141
2002 Prentice Hall. All rights reserved. 141 13.9 Multiple Document Interface (MDI) Windows Parent’s icons: minimize, maximize and close Maximized child’s icons: minimize, restore and close Minimized child’s icons: restore, maximize and close Parent’s title bar displays maximized child Fig. 13.33Minimized and maximized child windows.
142
2002 Prentice Hall. All rights reserved. 142 13.9 Multiple Document Interface (MDI) Windows Fig. 13.34Using MenuItem property MdiList. Separator bar and child windows 9 or more child windows enables the More Windows... option Child windows list
143
2002 Prentice Hall. All rights reserved. 143 13.9 Multiple Document Interface (MDI) Windows Fig. 13.35 LayoutMdi enumeration values (Part 1). ArrangeIconsCascade
144
2002 Prentice Hall. All rights reserved. 144 13.9 Multiple Document Interface (MDI) Windows Fig. 13.35 LayoutMdi enumeration values (Part 2). TileHorizontalTileVertical
145
2002 Prentice Hall. All rights reserved. Outline 145 UsingMDI.cs 1 // Fig. 13.36: UsingMDI.cs 2 // Demonstrating use of MDI parent and child windows. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class UsingMDI : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.MainMenu mainMenu1; 13 private System.Windows.Forms.MenuItem fileMenuItem; 14 private System.Windows.Forms.MenuItem newMenuItem; 15 private System.Windows.Forms.MenuItem child1MenuItem; 16 private System.Windows.Forms.MenuItem child2MenuItem; 17 private System.Windows.Forms.MenuItem child3MenuItem; 18 private System.Windows.Forms.MenuItem exitMenuItem; 19 private System.Windows.Forms.MenuItem formatMenuItem; 20 private System.Windows.Forms.MenuItem cascadeMenuItem; 21 private System.Windows.Forms.MenuItem 22 tileHorizontalMenuItem; 23 private System.Windows.Forms.MenuItem 24 tileVerticalMenuItem; 25 26 [STAThread] 27 static void Main() 28 { 29 Application.Run( new UsingMDI() ); 30 } 31 File menuNew submenu Exit submenu Formant menuCascade option Tiling options
146
2002 Prentice Hall. All rights reserved. Outline 146 UsingMDI.cs 32 // create Child 1 when menu clicked 33 private void child1MenuItem_Click( 34 object sender, System.EventArgs e ) 35 { 36 // create new child 37 Child formChild = new Child( "Child 1", 38 "\\images\\csharphtp1.jpg" ); 39 formChild.MdiParent = this; // set parent 40 formChild.Show(); // display child 41 } 42 43 // create Child 2 when menu clicked 44 private void child2MenuItem_Click( 45 object sender, System.EventArgs e ) 46 { 47 // create new child 48 Child formChild = new Child( "Child 2", 49 "\\images\\vbnethtp2.jpg" ); 50 formChild.MdiParent = this; // set parent 51 formChild.Show(); // display child 52 } 53 54 // create Child 3 when menu clicked 55 private void child3MenuItem_Click( 56 object sender, System.EventArgs e ) 57 { 58 // create new child 59 Child formChild = new Child( "Child 3", 60 "\\images\\pythonhtp1.jpg" ); 61 formChild.MdiParent = this; // set parent 62 formChild.Show(); // display child 63 } 64 Create child windows
147
2002 Prentice Hall. All rights reserved. Outline 147 UsingMDI.cs 65 // exit application 66 private void exitMenuItem_Click( 67 object sender, System.EventArgs e ) 68 { 69 Application.Exit(); 70 } 71 72 // set cascade layout 73 private void cascadeMenuItem_Click( 74 object sender, System.EventArgs e ) 75 { 76 this.LayoutMdi( MdiLayout.Cascade ); 77 } 78 79 // set TileHorizontal layout 80 private void tileHorizontalMenuItem_Click( 81 object sender, System.EventArgs e ) 82 { 83 this.LayoutMdi( MdiLayout.TileHorizontal ); 84 } 85 86 // set TileVertical layout 87 private void tileVerticalMenuItem_Click( 88 object sender, System.EventArgs e ) 89 { 90 this.LayoutMdi( MdiLayout.TileVertical ); 91 } 92 93 } // end class UsingMDI CascadeTile horizontallyTile vertically
148
2002 Prentice Hall. All rights reserved. Outline 148 UsingMDI.cs Program Output
149
2002 Prentice Hall. All rights reserved. Outline 149 Child.cs 1 // Fig. 13.37: Child.cs 2 // Child window of MDI parent. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.IO; 9 10 public class Child : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.PictureBox pictureBox; 13 14 public Child( string title, string fileName ) 15 { 16 // Required for Windows Form Designer support 17 InitializeComponent(); 18 19 Text = title; // set title text 20 21 // set image to display in pictureBox 22 pictureBox.Image = Image.FromFile( 23 Directory.GetCurrentDirectory() + fileName ); 24 } 25 } Create picture boxDisplay title Display picture Child class
150
2002 Prentice Hall. All rights reserved. 150 13.10 Visual Inheritance Create Form by inheriting from another Form –Derived Form inherits functionality of base Form –Derived Form inherits visual aspects of base Form
151
2002 Prentice Hall. All rights reserved. Outline 151 VisualInheritanc e.cs 1 // Fig. 13.38: VisualInheritance.cs 2 // Base Form for use with visual inheritance 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class VisualInheritance : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Label bugsLabel; 13 private System.Windows.Forms.Button learnMoreButton; 14 private System.Windows.Forms.Label label1; 15 16 [STAThread] 17 static void Main() 18 { 19 Application.Run( new VisualInheritance() ); 20 } 21 22 private void learnMoreButton_Click( object sender, 23 System.EventArgs e ) 24 { 25 MessageBox.Show( 26 "Bugs, Bugs, Bugs is a product of Bug2Bug.com", 27 "Learn More", MessageBoxButtons.OK, 28 MessageBoxIcon.Information ); 29 } 30 } Learn More display method
152
2002 Prentice Hall. All rights reserved. Outline 152 VisualInheritanc e.cs Program Output
153
2002 Prentice Hall. All rights reserved. 153 13.11 User-Defined Controls Fig. 13.39Visual Inheritance through the Form Designer.
154
2002 Prentice Hall. All rights reserved. Outline 154 VisualInheritanc eTest.cs 1 // Fig. 13.40: VisualInheritanceTest.cs 2 // Derived Form using visual inheritance. 3 using System; 4 using System.Collections; 5 using System.ComponentModel; 6 using System.Drawing; 7 using System.Windows.Forms; 8 9 public class VisualInheritanceTest : 10 VisualInheritance.VisualInheritance 11 { 12 private System.Windows.Forms.Button learnProgramButton; 13 14 // invoke when user clicks Learn the Program Button 15 private void learnProgramButton_Click( object sender, 16 System.EventArgs e ) 17 { 18 MessageBox.Show( 19 "This program was created by Deitel & Associates", 20 "Learn the Program", MessageBoxButtons.OK, 21 MessageBoxIcon.Information ); 22 } 23 24 public static void Main( string[] args ) 25 { 26 Application.Run( new VisualInheritanceTest() ); 27 } 28 } VisualInheritanceTest class is derived from VisualInheritance class Display message box
155
2002 Prentice Hall. All rights reserved. Outline 155 VisualInheritanc eTest.cs Program Output Derived class cannot modify these controls Derived class can modify this control
156
2002 Prentice Hall. All rights reserved. 156 13.11 User-Defined Controls Custom controls that inherit from other classes –Ex: can change appearance of a label
157
2002 Prentice Hall. All rights reserved. 157 13.11 User-Defined Controls
158
2002 Prentice Hall. All rights reserved. Outline 158 ClockUserControl.cs 1 // Fig. 13.42: ClockUserControl.cs 2 // User-defined control with a timer and a label. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Drawing; 8 using System.Data; 9 using System.Windows.Forms; 10 11 public class ClockUserControl 12 : System.Windows.Forms.UserControl 13 { 14 private System.Windows.Forms.Timer clockTimer; 15 private System.Windows.Forms.Label displayLabel; 16 17 // update label at every tick 18 private void clockTimer_Tick( 19 object sender, System.EventArgs e ) 20 { 21 // get current time (Now), convert to string 22 displayLabel.Text = DateTime.Now.ToLongTimeString(); 23 24 } // end method clockTimer_Tick 25 26 } // end class ClockUserControl TimerLabelUpdate label methodDisplay current time
159
2002 Prentice Hall. All rights reserved. 159 13.11 User-Defined Controls Fig. 13.43Custom-control creation.
160
2002 Prentice Hall. All rights reserved. 160 13.11 User-Defined Controls Fig. 13.44Project properties dialog.
161
2002 Prentice Hall. All rights reserved. 161 13.11 User-Defined Controls Fig. 13.45Custom control added to the ToolBox.
162
2002 Prentice Hall. All rights reserved. 162 13.11 User-Defined Controls Fig. 13.46Custom control added to a Form. New Toolbox icon Newly inserted control
163
2002 Prentice Hall. All rights reserved. 163 Homework and Practical Homework –Chapter 12 Self-review exercises –Chapter 13 Self-review exercises Practical –Exercise 12.3 (page 518) –Exercise 12.6 (page 518) –Exercise 12.7 (page 518) –Exercise 13.5 (page 589) –Exercise 13.6 (page 589) –Exercise 13.7 (page 589)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.