Chapter 13 – GUI: Part 2. 13.1Introduction 13.2 Menus 13.3 LinkLabel s 13.4 ListBox es and...

download Chapter 13 – GUI: Part 2. 13.1Introduction 13.2 Menus 13.3 LinkLabel s 13.4 ListBox es and CheckedListBox es 13.4.1 ListBoxes 13.4.2 CheckedListBoxes.

If you can't read please download the document

description

13.1Introduction Menu – Presents several logically organized options LinkLabel – Link to several destinations ListBox – Manipulate a list of values ComboBox – Drop-down lists

Transcript of Chapter 13 – GUI: Part 2. 13.1Introduction 13.2 Menus 13.3 LinkLabel s 13.4 ListBox es and...

Chapter 13 GUI: Part 2 13.1Introduction 13.2 Menus 13.3 LinkLabel s 13.4 ListBox es and CheckedListBox es ListBoxes CheckedListBoxes 13.5 ComboBox es 13.8 Tab Control 13.9 Multiple Document Interface (MDI) Windows Visual Inheritance User-Defined Controls Outline 13.1Introduction Menu Presents several logically organized options LinkLabel Link to several destinations ListBox Manipulate a list of values ComboBox Drop-down lists 13.2 Menus Menu provides groups of related commands. Menu items Commands or options in menu Sub-menu Menu within a menu Hot keys Alt key shortcuts Press Alt + underlined letter in desired menu item 13.2 Menus D C All menu items can have Alt key shortcuts which are accessed by pressing Alt and the underlined letter (for example, Alt + F expands the File menu). Some menu items display checkmarks, usually indicating that multiple options on the menu can be selected at once. Menus that are not top-level menus can have shortcut keys as well (combinations of Ctrl, Shift, Alt, F1, F2, letter keys, etc.). 13.2 Menus To create a menu, open the Toolbox and drag a MainStrip control onto the form. This creates a menu bar on the top of the form and places a MainStrip icon at the bottom of the IDE. To add command names to the menu, click the Type Here textbox and type the menu commands name. 13.2 Menus To create an access shortcut (or keyboard shortcut), type an ampersand (&) in front of the character to be underlined. For example, to create the File menu item, type &File. Separator bars are inserted by right-clicking the menu and selecting Insert Separator or by typing - for the menu text. Buttons also can have access shortcuts. Place the & symbol immediately before the desired character. To click the button, the user then presses Alt and the underlined character. It is convention to place an ellipsis () after a menu item that display a dialog (such as Save As...). 13.2 Menus 1 ' Fig 13.5: MenuTest.vb 2 ' Using menus to change font colors and styles. 3 4 Public Class FrmMenu 5 Private Sub mnuitmAbout_Click( _ 6 ByVal sender As System.Object, _ 7 ByVal e As System.EventArgs) Handles mnuitmAbout.Click 8 9 MessageBox.Show("This is an example" & vbCrLf & _ 10 "of using menus.", "About", MessageBoxButtons.OK, _ 11 MessageBoxIcon.Information) 12 End Sub ' mnuitmAbout_Click ' exit program 15 Private Sub mnuitmExit_Click( _ 16 ByVal sender As System.Object, _ 17 ByVal e As System.EventArgs) Handles mnuitmExit.Click Application.Exit() 20 End Sub ' mnuitmExit_Click Demo This event handler displays a message box when the about menu item in the file menu is clicked This event handler terminates the application when the exit menu item in the file menu is clicked 21 ' reset font color 22 Private Sub ClearColor() ' clear all checkmarks 25 mnuitmBlack.Checked = False 26 mnuitmBlue.Checked = False 27 mnuitmRed.Checked = False 28 mnuitmGreen.Checked = False 29 End Sub ' ClearColor ' update menu state and color display black 32 Private Sub mnuitmBlack_Click(ByVal sender As System.Object, _ 33 ByVal e As System.EventArgs) Handles mnuitmBlack.Click ' reset checkmarks for color menu items 36 ClearColor() ' set color to black 39 lblDisplay.ForeColor = Color.Black 40 mnuitmBlack.Checked = True 41 End Sub ' mnuitmBlack_Click Each color menu item must be mutually exclusive, so each event handler calls method ClearColor 42 ' update menu state and color display blue 43 Private Sub mnuitmBlue_Click(ByVal sender As System.Object, _ 44 ByVal e As System.EventArgs) Handles mnuitmBlue.Click ' reset checkmarks for color menu items 47 ClearColor() ' set color to blue 50 lblDisplay.ForeColor = Color.Blue 51 mnuitmBlue.Checked = True 52 End Sub ' mnuitmBlue_Click ' update menu state and color display red 55 Private Sub mnuitmRed_Click(ByVal sender As System.Object, _ 56 ByVal e As System.EventArgs) Handles mnuitmRed.Click ' reset checkmarks for color menu items 59 ClearColor() ' set color to red 62 lblDisplay.ForeColor = Color.Red 63 mnuitmRed.Checked = True 64 End Sub ' mnuitmRed_Click 65 ' update menu state and color display green 66 Private Sub mnuitmGreen_Click(ByVal sender As System.Object, _ 67 ByVal e As System.EventArgs) Handles mnuitmGreen.Click ' reset checkmarks for color menu items 70 ClearColor() ' set color to green 73 lblDisplay.ForeColor = Color.Green 74 mnuitmGreen.Checked = True 75 End Sub ' mnuitmGreen_Click ' reset font type 78 Private Sub ClearFont() ' clear all checkmarks 81 mnuitmTimes.Checked = False 82 mnuitmCourier.Checked = False 83 mnuitmComic.Checked = False 84 End Sub ' ClearFont 85 86 ' update menu state and set font to Times 87 Private Sub mnuitmTimes_Click(ByVal sender As System.Object, _ 88 ByVal e As System.EventArgs) Handles mnuitmTimes.Click ' reset checkmarks for font menu items 91 ClearFont() ' set Times New Roman font 94 mnuitmTimes.Checked = True 95 lblDisplay.Font = New Font("Times New Roman", 30, _ 96 lblDisplay.Font.Style) 97 End Sub ' mnuitmTimes_Click ' update menu state and set font to Courier 100 Private Sub mnuitmCourier_Click(ByVal sender As System.Object, _ 101 ByVal e As System.EventArgs) Handles mnuitmCourier.Click ' reset checkmarks for font menu items 104 ClearFont() ' set Courier font 107 mnuitmCourier.Checked = True 108 lblDisplay.Font = New Font("Courier New", 30, _ 109 lblDisplay.Font.Style) 110 End Sub ' mnuitmCourier_Click Each font menu item must be mutually exclusive, so each event handler calls method ClearFont ' update menu state and set font to Comic Sans MS 113 Private Sub mnuitmComic_Click(ByVal sender As System.Object, _ 114 ByVal e As System.EventArgs) Handles mnuitmComic.Click ' reset check marks for font menu items 117 ClearFont() ' set Comic Sans font 120 mnuitmComic.Checked = True 121 lblDisplay.Font = New Font("Comic Sans MS", 30, _ 122 lblDisplay.Font.Style) 123 End Sub ' mnuitmComic_Click ' toggle checkmark and toggle bold style 126 Private Sub mnuitmBold_Click( _ 127 ByVal sender As System.Object, _ 128 ByVal e As System.EventArgs) Handles mnuitmBold.Click ' toggle checkmark 131 mnuitmBold.Checked = Not mnuitmBold.Checked ' use Xor to toggle bold, keep all other styles 134 lblDisplay.Font = New Font( _ 135 lblDisplay.Font.FontFamily, 30, _ 136 lblDisplay.Font.Style Xor FontStyle.Bold) 137 End Sub ' mnuitmBold_Click ' toggle checkmark and toggle italic style 140 Private Sub mnuitmItalic_Click( _ 141 ByVal sender As System.Object, _ 142 ByVal e As System.EventArgs) Handles mnuitmItalic.Click ' toggle checkmark 145 mnuitmItalic.Checked = Not mnuitmItalic.Checked ' use Xor to toggle italic, keep all other styles 148 lblDisplay.Font = New Font( _ 149 lblDisplay.Font.FontFamily, 30, _ 150 lblDisplay.Font.Style Xor FontStyle.Italic) 151 End Sub ' mnuitmItalic_Click End Class ' FrmMenu 13.2 Menus Long Menu Example Public Class Form1 Private Sub MenuSize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuSize.Click If MenuSize.Text = "Short Menu" Then MenuSize.Text = "Long Menu" Else MenuSize.Text = "Short Menu" End If mFontUnderline.Visible = Not mFontUnderline.Visible mFontStrike.Visible = Not mFontStrike.Visible mFontSmallCaps.Visible = Not mFontSmallCaps.Visible mFontAllCaps.Visible = Not mFontAllCaps.Visible End Sub 13.3 LinkLabels LinkLabel Displays links to other resources Files Web pages Behavior similar to web page hyperlink Can change color New Previously visited 13.3 LinkLabels 1 ' Fig. 13.8: LinkLabelTest.vb 2' Using LinkLabels to create hyperlinks to C:\ drive,and Notepad 3 Public Class FrmLinkLabel 4 5 ' browse C:\ drive 6 Private Sub lnklblCDrive_LinkClicked( _ 7 ByVal sender As System.Object, ByVal e As _ 8 System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ 9 Handles lnklblCDrive.LinkClicked lnklblCDrive.LinkVisited = True 12 System.Diagnostics.Process.Start("C:\") 13 End Sub ' lnklblCDrive ' loadin Web browser 16 Private Sub lnklblDeitel_LinkClicked( _ 17 ByVal sender As System.Object, ByVal e As _ 18 System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ 19 Handles lnklblDeitel.LinkClicked lnklblDeitel.LinkVisited = True 22 System.Diagnostics.Process.Start( _ 23 "IExplore", "http://www.deitel.com") 24 End Sub ' lnklblDeitel Event handlers call method Start allowing execution of other programs from our application In this event handler method Start takes two arguments Method Start can take as arguments either the file to open (a String) or the application to run and its command-line arguments (two Strings). 25 ' run application Notepad 26 Private Sub lnklblNotepad_LinkClicked( _ 27 ByVal sender As System.Object, ByVal e As _ 28 System.Windows.Forms.LinkLabelLinkClickedEventArgs) _ 29 Handles lnklblNotepad.LinkClicked lnklblNotepad.LinkVisited = True ' run notepad application 34 ' full path not needed 35 System.Diagnostics.Process.Start("notepad") 36 End Sub ' lnklblNotepad_LinkClicked End Class ' LinkLabelList 13.3 LinkLabels 13.4 ListBoxes and CheckedListBoxes ListBox View and select from multiple items Scroll bar appears if necessary CheckedListBox Items have checkbox Select multiple items at same time Scroll bar appears if necessary 13.4 ListBoxes and CheckedListBoxes ListBoxes Items in a ListBox are referred by index. When items are added to the ListBox they are assigned an index. The first item in the ListBox always has an index of 0 the next 1 and so on. To add items to a ListBox or to a CheckedListBox we must add objects to its Items collection. This can be accomplished by calling method Add to add a String to the ListBoxs or CheckedListBoxs Items collection. For example, we could write myListBox.Items.Add( myListItem ) to add String myListItem to ListBox myListBox. To add multiple objects, programmers can either call method Add multiple times or call method AddRange to add an array of objects. Alternatively, we can add items to ListBoxes and CheckedListBoxes visually by examining the Items property in the Properties window ListBoxes Clicking the ellipsis button opens the String Collection Editor, a text area in which programmers add items; each item appears on a separate line 1 ' Fig : ListBoxTest.vb 2 ' Program to add, remove and clear list box items. 3 4 Public Class FrmListBox 5 6 ' add new item (text from input box) and clear input box 7 Private Sub cmdAdd_Click(ByVal sender As System.Object, _ 8 ByVal e As System.EventArgs) Handles cmdAdd.Click 9 10 lstDisplay.Items.Add(txtInput.Text) 11 txtInput.Text = "" 12 End Sub ' cmdAdd_Click ' remove item if one is selected 15 Private Sub cmdRemove_Click (ByVal sender As System.Object, _ 16 ByVal e As System.EventArgs) Handles cmdRemove.Click 17 ' remove only if item is selected 18 If lstDisplay.SelectedIndex -1 Then 19 lstDisplay.Items.RemoveAt(lstDisplay.SelectedIndex) 20 End If End Sub ' cmdRemove_Click 23 The cmdAdd_Click event handler calls method add, which takes the text from the text box as a String 24 clear all items 25 Private Sub cmdClear_Click (ByVal sender As System.Object, _ 26 ByVal e As System.EventArgs) Handles cmdClear.Click lstDisplay.Items.Clear() 29 End Sub ' cmdClear_Click ' exit application 32 Private Sub cmdExit_Click (ByVal sender As System.Object, _ 33 ByVal e As System.EventArgs) Handles cmdExit.Click Application.Exit() 36 End Sub ' cmdExit_Click End Class ' FrmListBox ListBoxes cmdAdd cmdRemove cmdClear cmdExit lstDisplay txtInput Demo ListBoxes Display the index of ListBox1 item in a TextBox1 and the item in TextBox2: Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _ ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedIndex Display the index TextBox2.Text = ListBox1.SelectedItem Display the item End Sub ListBoxes Display in a TextBox1 the number of Items in a ListBox1 when Button1 is clicked: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = ListBox1.Items.Count End Sub ListBoxes CheckedListBoxes Error message is generated if the programmer attempts to set the SelectionMode property to MultiSimple or MultiExtended in the Properties window of a CheckedListBox. The only choice is whether to give the user multiple selection or no selection at all. 1 ' Fig : CheckedListBoxTest.vb 2 ' Using the checked list boxes to add items to a list box. 3 4 Public Class FrmCheckedListBox 5 6 ' item about to change, add or remove from lstDisplay 7 Private Sub chklstInput_ItemCheck( _ 8 ByVal sender As System.Object, _ 9 ByVal e As System.Windows.Forms.ItemCheckEventArgs) _ 10 Handles chklstInput.ItemCheck ' obtain reference of selected item 13 Dim item As String = chklstInput.SelectedItem ' if item checked add to listbox 16 ' otherwise remove from listbox 17 If e.NewValue = CheckState.Checked Then 18 lstDisplay.Items.Add(item) 19 Else 20 lstDisplay.Items.Remove(item) 21 End If End Sub ' chklstInput_ItemCheck 24 End Class An If/Else control structure determines whether the user checked or unchecked an item in the CheckedListBox chklstInput lstDisplay Demo 13.5 ComboBoxes ComboBox Combines TextBox features with drop-down list Drop-down list Contains a list from which a value can be selected Scrollbar appears if necessary 13.5 ComboBoxes Style Simple does not display a drop-down arrow. Instead, a scrollbar appears next to the control, allowing the user to select a choice from the list. The user also can type in a selection. 1 ' Fig : ComboBoxTest.vb 2 ' Using ComboBox to select shape to draw. 3 4 Imports System.Drawing 5 6 Public Class FrmComboBox 7 8 ' get selected index, draw shape 9 Private Sub cboImage_SelectedIndexChanged( _ 10 ByVal sender As System.Object, _ 11 ByVal e As System.EventArgs) _ 12 Handles cboImage.SelectedIndexChanged ' create graphics object, pen and brush 15 Dim myGraphics As Graphics = Me.CreateGraphics() ' create Pen using color DarkRed 18 Dim myPen As New Pen(Color.DarkRed) ' create SolidBrush using color DarkRed 21 Dim mySolidBrush As New SolidBrush(Color.DarkRed) ' clear drawing area by setting it to color White 24 myGraphics.Clear(Color.White) Event handler cboImage_SelectedIndexChange handles the SelectedIndexChange events generated when a user selects an item from the combo box The program allows users to select a shape to draw an empty or filled circle, ellipse, square or pieby using a ComboBox. 25 ' find index, draw proper shape 26 Select Case cboImage.SelectedIndex 27 Case 0 ' case circle is selected 28 myGraphics.DrawEllipse(myPen, 50, 50, 150, 150) Case 1 ' case rectangle is selected 31 myGraphics.DrawRectangle(myPen, 50, 50, 150, 150) Case 2 ' case ellipse is selected 34 myGraphics.DrawEllipse(myPen, 50, 85, 150, 115) Case 3 ' case pie is selected 37 myGraphics.DrawPie(myPen, 50, 50, 150, 150, 0, 45) Case 4 ' case filled circle is selected 40 myGraphics.FillEllipse( mySolidBrush, 50, 50, 150, 150) Case 5 ' case filled rectangle is selected 43 myGraphics.FillRectangle( mySolidBrush, 50, 50, 150, 150) Case 6 ' case filled ellipse is selected 46 myGraphics.FillEllipse( mySolidBrush, 50, 85, 150, 115) Case 7 ' case filled pie is selected 49 myGraphics.FillPie( mySolidBrush, 50, 50, 150, 150, 0, 45) End Select 52 End Sub ' cboImage_SelectedIndexChanged 53 End Class ' FrmComboBox A select case structure is used to determine what item was selected 13.5 ComboBoxes cboImage Demo 13.5 ComboBoxes 13.8 Tab Control TabControl Creates tabbed windows Saves space using TabPage objects TabPage objects Similar to Panels and GroupBoxes Can contain controls 13.8 Tab Control 1 ' Fig : UsingTabs.vb 2 ' Using TabControl to display various font settings. 3 4 Public Class FrmTabs 5 ' event handler for black radio button 6 Private Sub radBlack_CheckedChanged( _ 7 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 8 Handles radBlack.CheckedChanged 9 lblDisplay.ForeColor = Color.Black 10 End Sub ' radBlack_CheckedChanged ' event handler for red radio button 13 Private Sub radRed_CheckedChanged( _ 14 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 15 Handles radRed.CheckedChanged lblDisplay.ForeColor = Color.Red 18 End Sub ' radRed_CheckedChanged ' event handler for green radio button 21 Private Sub radGreen_CheckedChanged( _ 22 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 23 Handles radGreen.CheckedChanged lblDisplay.ForeColor = Color.Green 26 End Sub ' radGreen_CheckedChanged tbpColor tbpSize tbpMessage tbpAbout 27 ' event handler for size 12 radio button 28 Private Sub radSize12_CheckedChanged( _ 29 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 30 Handles radSize12.CheckedChanged lblDisplay.Font = New Font(lblDisplay.Font.Name, 12) 33 End Sub ' radSize12_CheckedChanged ' event handler for size 16 radio button 36 Private Sub radSize16_CheckedChanged( _ 37 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 38 Handles radSize16.CheckedChanged lblDisplay.Font = New Font(lblDisplay.Font.Name, 16) 41 End Sub ' radSize16_CheckedChanged ' event handler for size 20 radio button 44 Private Sub radSize20_CheckedChanged( _ 45 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 46 Handles radSize20.CheckedChanged lblDisplay.Font = New Font(lblDisplay.Font.Name, 20) 49 End Sub ' radSize20_CheckedChanged 50 ' event handler for message "Hello!" radio button 51 Private Sub radHello_CheckedChanged( _ 52 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 53 Handles radHello.CheckedChanged lblDisplay.Text = "Hello!" 56 End Sub ' radHello_CheckedChanged ' event handler for message "Goodbye!" radio button 59 Private Sub radGoodbye_CheckedChanged( _ 60 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 61 Handles radGoodbye.CheckedChanged lblDisplay.Text = "Goodbye!" 64 End Sub ' radGoodbye_CheckedChanged End Class ' FrmTabs 13.8 Tab Control Demo Single Document Interface (SDI) A program that can only support one open window or a document For Example, paint and Notepad are SDIs MDI programs enable users to edit multiple documents at once. For example, Photoshop and Adobe Acrobat Reader are MDIs 13.9 Multiple Document Interface (MDI) Windows Single Document Interface (SDI) Multiple Document Interface (MDI) Cont. The application window of an MDI program is called the parent window. Each window inside the application is referred to as a child window. Cont MDI Allows multiple windows Parent window Application window Can have many child windows Child window Cannot be parent Has exactly one parent Cannot be moved outside parent Functionality can be different than other child windows from same parent Cont. How to create and MDI form? To create and MDI form, create a new form and set its IsMDIContainer property to True. The form will then change appearance How to create a child? Next, create a child form class to be added to the form. To do this, right-click the project in the Solution Explorer, select Add Windows Form... and name the file. Cont. To add the child form to the parent, we must create a new child form object, set its MDIParent property to the parent form and call method Show: Dim frmChild As New ChildFormClass() frmChild.MdiParent = frmParent frmChild.Show() Cont. Child windows can be minimized, maximized and closed independently of each other and of the parent window. When the parent is minimized or closed, the child windows are minimized or closed as well. 13.9 Multiple Document Interface (MDI) Windows MenuItem properties The parent and child forms can have different menus, which are merged whenever a child window is selected. MergeOrder and the MergeType properties for each MenuItem specify how the parent and child menus are merged. Cont. MergeOrder determines the order in which MenuItems appear when two menus are merged. MenuItems with a lower MergeOrder value appear first. Cont. For example, Menu1 has items File, Edit and Window (and their orders are 0, 10 and 20). Menu2 has items Format and View (and their orders are 7 and 15). Merged menu contains menu items File, Format, Edit, View and Window, in that order Cont. Each MenuItem instance has its own MergeOrder property. It is likely that, at some point in an application, two MenuItems with the same MergeOrder value will merge. Property MergeType resolves this conflict by determining the order in which the two menus are displayed. MergeType The MergeType property takes a MenuMerge enumeration value and determines which menu items are displayed when two menus are merged. MergeType Values Enumeration valuePerformace AddA menu item with value Add is added to its parents menu as a new menu on the menu bar (the parents menu items come first) ReplaceIf a child forms menu item has value Replace, it attempts to take the place of its parent forms corresponding menu item during merging MergeItemsA menu with value MergeItems combines its items with that of its parents corresponding menu (if parent and child menus originally occupy the same space, their submenus are combined as one menu) RemoveA childs menu item with value Remove disappears when the menu is merged with that of its parent. MdiList Property VB.NET provides a property that facilitates the tracking of which child windows are opened in an MDI container. Property MdiList (a Boolean) of class Menu- Item determines whether a MenuItem displays a list of open child windows. The list appears at the bottom of the menu following a separator bar When a new child window is opened, an entry is added to the list. If nine or more child windows are open, the list includes the option More Windows..., which allows the user to select a window from a list, using a scrollbar. Multiple MenuItems can have their MdiList property set; each displays a list of open child windows. MdiList Property LayoutMdi Property MDI containers allow developers to organize the placement of child windows. The child windows in an MDI application can be arranged by calling method LayoutMdi of the parent form. Method LayoutMdi takes a LayoutMdi enumeration, which can have values ArrangeIcons, Cascade, TileHorizontal and TileVertical. 1 ' Fig : UsingMDI.vb 2 ' Demonstrating use of MDI parent and child windows. 3 4Public Class FrmUsingMDI 5Private childWindow as FrmChild 6 ' create Child1 when menu clicked 7 Private Sub mnuitmChild1_Click( _ 8 ByVal sender As System.Object, _ 9 ByVal e As System.EventArgs) Handles mnuitmChild1.Click ' create image path 12 Dim imagePath As String = _ 13 Directory.GetCurrentDirectory() & "\images\image0.jpg" ' create new child 16 childWindow = New FrmChild(imagePath, "Child1") 17 childWindow.MdiParent = Me ' set parent 18 childWindow.Show() ' display child 19 End Sub ' mnuitmChild1_Click ' create Child2 when menu clicked 22 Private Sub mnuitmChild2_Click( _ 23 ByVal sender As System.Object, _ 24 ByVal e As System.EventArgs) Handles mnuitmChild2.Click 25 ' create image path 26 Dim imagePath As String = _ 27 Directory.GetCurrentDirectory() & "\images\image1.jpg" ' create new child 30 childWindow = New FrmChild(imagePath, "Child2") 31 childWindow.MdiParent = Me ' set parent 32 childWindow.Show() ' display child 33 End Sub ' mnuitmChild2_Click ' create Child3 when menu clicked 36 Private Sub mnuitmChild3_Click( _ 37 ByVal sender As System.Object, _ 38 ByVal e As System.EventArgs) Handles mnuitmChild3.Click ' create image path 41 Dim imagePath As String = _ 42 Directory.GetCurrentDirectory() & "\images\image2.jpg" 43 ' create new child 44 childWindow = New FrmChild(imagePath, "Child3") 45 childWindow.MdiParent = Me ' set parent 46 childWindow.Show() ' display child 47 End Sub ' mnuitmChild3_Click 48 ' exit application 49 Private Sub mnuitmExit_Click(ByVal sender As System.Object, _ 50 ByVal e As System.EventArgs) Handles mnuitmExit.Click Application.Exit() 53 End Sub ' mnuitmExit_Click ' set cascade layout 55 Private Sub mnuitmCascade_Click(ByVal sender As System.Object, _ 56 ByVal e As System.EventArgs) Handles mnuitmCascade.Click Me.LayoutMdi(MdiLayout.Cascade) 59 End Sub ' mnuitmCascade_Click ' set TileHorizontal layout 62 Private Sub mnuitmTileHorizontal_Click( _ 63 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 64 Handles mnuitmTileHorizontal.Click Me.LayoutMdi(MdiLayout.TileHorizontal) 67 End Sub ' mnuitmTileHorizontal_Click Method LayoutMdi can take values ArrangeIcons, Cascade, TileHorizontal and TileVertical 68 ' set TileVertical layout 69 Private Sub mnuitmTileVertical_Click( _ 70 ByVal sender As System.Object, _ 71 ByVal e As System.EventArgs) Handles mnuitmTileVertical.Click Me.LayoutMdi(MdiLayout.TileVertical) 74 End Sub ' mnuitmTileVertical_Click End Class ' FrmUsingMDI 13.9 Multiple Document Interface (MDI) Windows Demo Extra topic: Working with Forms 1 -Adding a New Form to the Project You can add a new form to the project with which you are working. To do that, right click on the project name>Add Select Windows Form from the window and click Add to add a new form to the project. To run the application with other Startup object: Right-click on the project name in Solution Explorer window and select Properties which displays the Property Pages window. On this window click the drop- down box which is labeled as Startup Object. Doing that displays all the forms available in the project. Select the form which you want to be displayed when you run the application. Now, when you run the application, the form you assigned as Startup object will be displayed. 2- Working with Multiple Forms Public Class Form1 Private Sub btnFrm2_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles btnFrm2.Click Form2.Show() Me.Hide() Form3.Hide() End Sub Private Sub btnFrm3_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles btnFrm3.Click Form3.Show() Me.Hide() Form2.Hide() End Sub End Class Public Class Form2 Private Sub btnFrm1_Click(ByVal _ sender As System.Object, ByVal e As _ System.EventArgs) Handles _ btnFrm1.Click Form1.Show() Me.Hide() End Sub End Class Public Class Form3 Private Sub btnFrm1_Click(ByVal _ sender As System.Object, ByVal e As _ System.EventArgs) Handles _ btnFrm1.Click Form1.Show() Me.Hide() End Sub End Class Reading Topics For more information on how to Access Controls on Other Forms:For more information on how to Use Events in Multiple Forms: In OOP, Inheritance is the ability to use all of the functionality of an existing class, and extend those capabilities without re-writing the original class. In.NET, inheritance is not just limited to designing classes but also extended to visual designing. So, what does it mean? Well, it means we can use inheritance in Form designing too, so this kind of usage is called Visual Inheritance. One of the main advantages of visual inheritance is it reduces or cuts down the development time, and helps in designing consistency in the Forms layouts Visual Inheritance Derived forms contain same functionality as Base form including: Properties Methods Variables Controls All visual aspects Sizing Layout Spacing Colors and fonts 1 ' Fig : FrmInheritance.vb 2 ' Form template for use with visual inheritance. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmInheritance 7 Inherits Form 8 9 ' invoked when user clicks Learn More button 10 Private Sub cmdLearn_Click(ByVal sender As System.Object, _ 11 ByVal e As System.EventArgs) Handles cmdLearn.Click MessageBox.Show("Bugs, Bugs, Bugs is a product of " & _ 14 " Bug2Bug.com.", "Learn More", MessageBoxButtons.OK, _ 15 MessageBoxIcon.Information) 16 End Sub ' cmdLearn_Click End Class ' FrmInheritance lblBug lblCopyright cmdLearn Example: 1- Create the Base Form Demo Example: 2- Run the Base Form to make sure it runs correctly To allow other forms to inherit from FrmInheritance, we must package FrmInheritance as a.dll. Right click the project's name in the Solution Explorer and choose Properties. Example: 3- Package the Base Form Under Application > Application Type, change Type to Class Library. Building the project produces the.dll. To visually inherit from FrmInheritance, we create an empty project. From the Project menu, select Add Inherited Form... to display the Add New Item dialog. Select Inherited Form from the Templates pane. Clicking OK displays the Inheritance Picker tool. Example: 4- Create an empty project to make the derived form The Inheritance Picker tool enables programmers to create a form which inherits from a specified form. Click button Browse and select the.dll file corresponding to FrmInheritance. This.dll file normally is located within the projects bin directory. Click OK. The Form Designer should now display the inherited form We can add components to the form. In the design view Visual Studio adds Glyphs to the image to let you know that these components are inherited, not actually in this form No Glyphs, it is not inherited 1 ' Fig : VisualTest.vb 2 ' A form that uses visual inheritance. 3 4 Public Class FrmVisualTest 5 Inherits VisualForm.FrmInheritance ' invoke when user clicks Learn the Program button 9 Private Sub cmdProgram_Click(ByVal sender As System.Object, _ 10 ByVal e As System.EventArgs) Handles cmdProgram.Click MessageBox.Show( _ 13 "This program was created by Deitel & Associates", _ 14 "Learn the Program", MessageBoxButtons.OK, _ 15 MessageBoxIcon.Information) 16 End Sub ' cmdProgram_Click End Class ' FrmVisualTest Components, layout and functionality of the base form are inherited by the new form cmdProgram new button added to form Example: 5- Add new controls to the derived form Demo The.NET Framework allows programmers to create customized controls that inherit from a variety of classes. These customized controls appear in the users Toolbox and can be added to Forms, Panels or GroupBoxes in the same way that we add Buttons, Labels, and other predefined controls. The simplest way to create a customized control is to derive a class from an existing Windows Forms control, such as a Label. For example, we can create a new type of label that behaves like a normal Label but has a different appearance. We accomplish this by inheriting from class Label and overriding method OnPaint User-Defined Controls Custom controls techniques: 1.Inherit from class Control Define a brand new control 2.Inherit from Windows Forms control Add functionality to preexisting control 3.Create a UserControl Multiple preexisting controls 13.11 User-Defined Controls Example: Create a clock control. It should be a UserControl composed of a label and a timer whenever the timer raises an event, the label is updated to reflect the current time User-Defined Controls Demo 1 - create a UserControl class for the project by selecting Project > Add User Control.... This displays a dialog from which we can select the type of control to add user controls are already selected. 2- We then name the file (and the class) CClockUserControl User-Defined Controls This brings up our empty CClockUserControl as a grey rectangle. 1 ' Fig 13.43: CClockUserControl.vb 2 ' User-defined control with timer and label. 3 ' create clock control that inherits from UserControl 4 Imports System.Windows.Forms 5 Public Class CClockUserControl 6 Inherits UserControl 7 8 ' update label at every tick 9 Private Sub tmrClock_Tick(ByVal sender As System.Object, _ 10 ByVal e As System.EventArgs) Handles tmrClock.Tick ' get current time (Now), convert to string 13 lblDisplay.Text = DateTime.Now.ToLongTimeString 14 End Sub ' tmrClock_Tick 15 End Class ' CClockUserControl 3- Add a Label (lblDisplay) and a Timer (tmrClock) to the UserControl. Then set the Timer interval to 100 milliseconds and set lblDisplays text with each event. DateTime contains member Now, which is the current time. Method ToLongTimeString converts Now to a String containing the current hour, minute and second (along with AM or PM). 4 -Note that tmrClock must be enabled by setting property Enabled to True in the Properties window. 5- Add new Windows Applaication form. You will see our clock control appears as an item on the ToolBox. To use the control, we can simply drag it onto a form and run the Windows application. The CClockUserControl object has a white background to make it stand out in the form User-Defined Controls The above steps are useful when we need to define a custom control for the project on which we are working on. Visual Studio.NET allows developers to share their custom controls with other developers. To create a UserControl that can be exported to other solutions, do the following: 1. Create a new Windows Control Library project. 2. Inside the project, add controls and functionality to the UserControl User-Defined Controls 3. Build the project. Visual Studio.NET creates a.dll file for the UserControl in the output directory. The file is not executable. Select Project > Properties to find the output directory and output file. 4. Create a new Windows application. 5. Import the UserControl. In the new Windows application, right click the ToolBox, and select Customize Toolbox.... In the dialog that appears, select the.NET Framework Components tab. Browse for the.dll file, which is in the output directory for the Windows control library project. Click the checkbox next to the control, and click OK User-Defined Controls 6. The UserControl appears on the ToolBox and can be added to the form as if it were any other control User-Defined Controls Control classes do not have a Main method they cannot be run by themselves. To test their functionality, add them to a sample Windows application and run them there User-Defined Controls Example Create a UserControl called LoginPasswordUserControl. The LoginPasswordUserControl contains the following: o Label (loginLabel) that displays String Login:. o TextBox (loginTextBox) where the user enters a login name. o Label (passwordLabel) that displays the String Password: o TextBox (passwordTextBox) where a user inputs a password LoginPasswordUserControl must provide Public read-only properties Login and Password that allow an application to retrieve the user input from a login TextBox. Use the new control in application that displays the values input by the LoginPasswordUserControl. 125 126Solution In order to create LoginPasswordUserControl application, do the following: (Class Library) 1.Custom control (Class Library) Create your custom control LoginPasswordUserControl from other predefined controls, TextBoxes and Labels and add required functionality to it. Then it will appears in the users ToolBox. (Windows application) 2.Application (Windows application) Share the LoginPasswordUserControl by adding it into a Form and add more controls and functionalities. 1.Create a new Class Library named LoginPasswordUserControl. 2. Delete the file named Class1.vb that is initially provided with the project. 3- Right click the project in the Solution Explorer and select Add> User Control in the dialog that appears, name the user control LoginPasswordUserControl file and click Add. 130 Class Library 4.Design the user control by adding the required controls. TextBox Name: loginTextBox TextBox Name: passwardTextBox Label Name: loginLabel Label Name: passwardLabel 131 Change the PasswardChar property of the passwardTextBox to * . In order for the TextBoxes to change in the Windows application; change its Modefier property to Public Build the project and the Visual Studio will create a.dll file in the solutions bin/Release directory. ( Note: class libraries are not executable files, they are used to define classes that are reused on other executable applications) 1.Create a Windows application and name it LoginPasswordUserControlApp. Windows Application 134 Windows Application 2. Right click the Toolbox and select Choose Items 135 In the dialog, click Browse and locate the.dll file for the class library you already created in the Class Library (step 6). The item will then appear in the Choose ToolBox Items dialog. If it is not already checked, check this item. 136 Note: By completing step 2, the user control is now listed in the Toolbox, and can be added to the any Form as if it were any other control. You may add more controls and functionality to the Form as needed. 137 3.Add a Button OK to your Form. 4.Add functionality to your controls, by adding the following: Build and debug Demo User Defined Data Types Structure CheckRecord Dim CheckNumber as Integer Dim CheckDate as Date Dim CheckAmount as Single Dim CheckPaidTo as String End Structure Must appear outside any procedures Dim check1,check2 as CheckRecord check1.CheckNumber = 275 check1.CheckDate = #09/12/2001# check1.CheckAmount = check1.CheckPaidTo = Gas Co. Structure CheckRecord Dim CheckNumber as Integer Dim CheckDate as Date Dim CheckAmount as Single Dim CheckPaidTo as String End Structure User Defined Data Types Dim checks(100) As CheckRecord Checks (1).CheckNumber = 275 Checks (1).CheckDate = #09/12/2001# Checks (1).CheckAmount = Checks (1).CheckPaidTo = Gas Co.