Unit4: Functions, Built-In Dialog Boxes, Menus and 1

Unit 4

Functions, Built-In Dialog Boxes, Menus and Toolbar

Topic Contents:

• Menus and - Strip, Tool Strip, Status Strip • Built-In Dialog Boxes – Open File Dialogs, Save File Dialogs, Font Dialogs, Color Dialogs, Print Dialogs, InputBox, MsgBox, • Interfacing With End user- Creating MDI Parent and Child, Functions • Procedures- Built-In Functions- Mathematical and String Functions, User Defined Functions and Procedures .

Menus Menus are a part of every good application and provide not only an easy way to navigate within an application but also useful tools for working with that application. The MenuStrip control in Visual Studio, provides several key features. First and foremost, it provides a quick and easy way to add menus, menu items, and submenu items to your application. It also provides a built-in editor that enables you to add, edit, and delete menu items at the drop of a hat. The menu items that you create may contain images, access keys, shortcut keys, and check marks as well as text labels.

• Visual Basic has come a long way and now provides an Image property for a menu item that makes adding an image to your menu items a breeze. • An access key (also known as an accelerator key ) enables you to navigate the menus using the Alt key and a letter that is underlined in the menu item. When the access key is pressed, the menu appears on the screen, and the user can navigate through it using the arrow keys or the mouse. • Shortcut keys enable you to invoke the menu item without displaying the menus at all. Shortcut keys usually consist of a control key and a letter, such as Ctrl +X to cut text. • A check mark symbol can be placed next to a menu item in lieu of an image, typically to indicate that the menu item is being used.

CREATING MENUS The MenuStrip control represents the container for the menu structure. The MenuStrip control work as the top-level container for the menu structure. The ToolStripMenuItem class and the

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 2

ToolStripDropDownMenu class provide the functionalities to create menu items, sub menus and drop-down menus. Following are the steps to create a menu in VB.Net

• Start Visual Studio 2010 and click File ➪ New Project. In the New Project dialog, select Windows Forms Application • Drag a MenuStrip control from the Toolbox and drop it on your form. It is automatically positioned at the top of your form. • Click the MenuStrip1 control on the form and then type the menu item name .Menu items are added automatically. Or in the Properties , click the items with the ellipses next to the Items property • In the Items Collection Editor , click the Add button to add a new menu item. • To add submenu items click on the menu item and then click on add button in the Items Collection Editor. • Then Click on OK Button

ToolBars ToolBar control is used to change both the color of the text in your and the case of the text to either all uppercase letters or all lowercase letters.

Creating the toolbar The toolbar you are building will contain a collection of buttons, like the toolbar in Visual Studio .

1. Return to the Forms Designer in the Windows Forms Text Editor project. Select the ToolStrip control from the Toolbox and drag and drop it on the form. It will automatically dock at the top of the form. 2. To add buttons to the toolbar you use a built-in editor. Find the Items property in the Properties window, select it, and left-click the collection button to the right of (Collection)(look for . . . ). 3. Add buttons to the toolbar. To add the first button, click the Add button in the Items Collection Editor. The ItemsCollection Editor displays a properties palette much like the one that you’re used to using. For each button you need to change its name, change its display style, give it an , clear its text, and provide some explanatory text. 4. You want to create a Separator between the buttons add a control using the Add ToolStripButton tool. Select the ToolStrip at the top of the form. You will see the drop-down to add a new item. Open the drop-down and select Separator. A Separator will be added to the ToolStrip. You can accept all the default properties for this button.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 3

5. Click the OK button in the Items Collection Editor to close it.

Status Bar The control will also be used in your project to display the status of your actions as a result of clicking a button on the toolbar. The status bar is a panel that sits at the bottom of an application window and tells the user what’s going on.

Adding a Status Bar 1. Return to your Windows Forms Text Editor project, drag a StatusStrip control from the Toolbox, and drop it onto your form. You’ll notice that it automatically docks itself to the bottom edge of the form and you’ll only be able to change the height portion of its Size property if desired. 2. You need to add one StatusStripLabel to the Items collection of the StatusStrip so that you can display text on the status bar. Use the drop-down in the StatusStrip and select StatusLabel to add one. 3. You can also use the Items Collection Editor dialog for the Status Strip . 4. Then click the OK button to close the Collection Editor

The Built-in Dialog Boxes There are a number of built-in dialog boxes in Visual Basic, which is great, because developing your own file open, file save, and other dialog boxes not only takes a lot of work, but gives your program a different look from what Windows users are already used to. All of these dialog box control classes inherit from the CommonDialog class and override the RunDialog() function of the base class to

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 4

create the specific dialog box. The RunDialog() function is automatically invoked when a user of a dialog box calls its ShowDialog() function.

The ShowDialog method is used to display all the dialog box controls at run time. It returns a value of the type of DialogResult enumeration. The values of DialogResult enumeration are:

• Abort - returns DialogResult.Abort value, when user clicks an Abort button. • Cancel - returns DialogResult.Cancel, when user clicks a Cancel button. • Ignore - returns DialogResult.Ignore, when user clicks an Ignore button. • No - returns DialogResult.No, when user clicks a No button. • None - returns nothing and the dialog box continues running. • OK - returns DialogResult.OK, when user clicks an OK button • Retry - returns DialogResult.Retry , when user clicks an Retry button • Yes - returns DialogResult.Yes, when user clicks an Yes button

The following diagram shows the common dialog class inheritance:

All these above mentioned classes have corresponding controls that could be added from the Toolbox during design time. You can include relevant functionality of these classes to your application, either by instantiating the class programmatically or by using relevant controls.

When you double click any of the dialog controls in the toolbox or drag the control onto the form, it appears in the Component tray at the bottom of the Windows Forms Designer, they do not directly show up on the form.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 5

There are various dialog boxes in VB.NET

• Open File dialogs • Save File dialogs • Font dialogs • Color dialogs • Print dialogs

OpenFileDialog Control The OpenFileDialog control prompts the user to open a file and allows the user to select a file to open. The user can check if the file exists and then open it. The OpenFileDialog control class inherits from the abstract class FileDialog . Following is the Open box:

Properties of the OpenFileDialog Control The following are some of the commonly used properties of the OpenFileDialog control:

S.N Property Description

1 AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.

2 AutoUpgradeEnabled Gets or sets a value indicating whether this FileDialog instance should automatically upgrade appearance and

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 6

behavior when running on Windows Vista.

3 CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

4 CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

5 FileName Gets or sets a string containing the file name selected in the file dialog box.

6 FileNames Gets the file names of all selected files in the dialog box.

7 Filter Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

8 ReadOnlyChecked Gets or sets a value indicating whether the read -only check box is selected.

9 ShowHelp Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

10 ShowReadOnly Gets or sets a value indicating whether the dialog box contains a read-only check box.

11 Title Gets or sets the file dialog box title.

12 ValidateNames Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

Methods of the OpenFileDialog Control The following are some of the commonly used methods of the OpenFileDialog control:

Sr.No Method Name & Description

1 OpenFile Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

2 Reset Resets all options to their default value.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 7

Example In this example, let's load an image file in a picture box, using the open file dialog box. Take the following steps:

• Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form. • Set the Text property of the button control to 'Load Image File'. • Double-click the Load Image File button and modify the code of the Click event:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName) End If End Sub

ColorDialog Control The ColorDialog control class represents a common dialog box that displays available colors along with controls that enable the user to define custom colors. It lets the user select a color.

The main property of the ColorDialog control is Color , which returns a Color object.

Following is the Color dialog box:

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 8

The following are some of the commonly used properties of the ColorDialog control:

S.N Property Description

1 AllowFullOpen Gets or sets a value indicating whether the user can use the dialog box to define custom colors.

2 AnyColor Gets or sets a value indicating whether the dialog box displays all available colors in the set of basic colors.

3 CanRaiseEvents Gets a value indicating whether the component can raise an event.

4 Color Gets or sets the color selected by the user.

5 CustomColors Gets or sets the set of custom colors shown in the dialog box.

6 FullOpen Gets or sets a value indicating whether the controls used to create custom colors are visible when the dialog box is opened

7 ShowHelp Gets or sets a value indicating whether a Help button appears in the color dialog box.

8 SolidColorOnly Gets or sets a value indicating whether the dialog box will restrict users to selecting solid colors only.

Methods of the ColorDialog Control The following are some of the commonly used methods of the ColorDialog control:

S.N Method Name & Description

1 Reset Resets all options to their default values, the last selected color to black, and the custom colors

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 9

to their default values.

2 RunDialog When overridden in a derived class, specifies a common dialog box.

3 ShowDialog Runs a common dialog box with a default owner.

Events of the ColorDialog Control The following are some of the commonly used events of the ColorDialog control:

S.N Event Description

1 HelpRequest Occurs when the user clicks the Help button on a common dialog box.

Example In this example, let's change the fore color of a label control using the color dialog box. Take the following steps:

1. Drag and drop a label control, a button control and a ColorDialog control on the form. 2. Set the Text property of the label and the button control to 'Give me a new Color' and 'Change Color' respectively. 3. Change the font of the label as per your likings 4. Double-click the Change Color button and modify the code of the Click event:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then Label1.ForeColor = ColorDialog1.Color End If End Sub

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 10

Clicking on the Change Color button, the color dialog appears, select a color and click the OK button. The selected color will be applied as the fore color of the text of the label.

FontDialog Control It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color. It returns the Font and Color objects.

Following is the Font dialog box:

By default the Color ComboBox is not shown on the Font dialog box. You should set the ShowColor property of the FontDialog control to be True .

Properties of the FontDialog Control

The following are some of the commonly used properties of the FontDialog control:

S.N Property Description

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 11

1 AllowSimulations Gets or sets a value indicating whether the dialog box allows graphics device interface (GDI) font simulations.

2 AllowVectorFonts Gets or sets a value indicating whether the dialog box allows vector font selections.

3 AllowVerticalFonts Gets or sets a value indicating whether the dialog box displays both vertical and horizontal fonts, or only horizontal fonts.

4 Color Gets or sets the selected font color.

5 FixedPitchOnly Gets or sets a value indicating whether the dialog box allows only the selection of fixed-pitch fonts.

6 Font Gets or sets the selected font.

7 FontMustExist Gets or sets a value indicating whether the dialog box specifies an error condition if the user attempts to select a font or style that does not exist.

8 Max Size Gets or sets the maximum point size a user can select.

9 MinSize Gets or sets the minimum point size a user can select.

10 ScriptsOnly Gets or sets a value indicating whether the dialog box allows selection of fonts for all non-OEM and Symbol character sets, as well as the ANSI character set.

11 ShowApply Gets or sets a value indicating whether the dialog box contains an Apply button.

12 ShowColor Gets or sets a value indicating whether the dialog box displays the color choice.

13 ShowEffect s Gets or sets a value indicating whether the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options.

14 ShowHelp Gets or sets a value indicating whether the dialog box displays a Help button.

Methods of the FontDialog Control

The following are some of the commonly used methods of the FontDialog control:

S.N Method Name & Description

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 12

1 Reset Resets all options to their default values.

2 RunDialog When overridden in a derived class, specifies a common dialog box.

3 ShowDialog Runs a common dialog box with a default owner.

Events of the FontDialog Control

The following are some of the commonly used events of the FontDialog control:

S.N Event Description

1 Apply Occurs when the Apply button on the font dialog box is clicked.

Example In this example, let's change the font and color of the text from a rich text control using the Font dialog box. Take the following steps:

1. Drag and drop a RichTextBox control, a Button control and a FontDialog control on the form. 2. Set the Text property of the button control to 'Change Font'. 3. Set the ShowColor property of the FontDialog control to True. 4. Double-click the Change Color button and modify the code of the Click event:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then RichTextBox1.ForeColor = FontDialog1.Color RichTextBox1.Font = FontDialog1.Font End If End Sub

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 13

SaveFileDialog Control The SaveFileDialog control prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. The SaveFileDialog control class inherits from the abstract class FileDialog.

Following is the Save File dialog box:

Properties of the SaveFileDialog Control The following are some of the commonly used properties of the SaveFileDialog control:

S.N Property Description

1 AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 14

2 CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

3 CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

4 CreatePrompt Gets or sets a value indicating whether the dialog box prompts the user for permission to create a file if the user specifies a file that does not exist.

5 DefaultExt Gets or sets the default file name extension.

6 DereferenceLinks Gets or sets a value indicating whether the dialog box returns the location of the file referenced by the shortcut or whether it returns the location of the shortcut (.lnk).

7 FileName Gets or sets a string containing the file name selected in the file dialog box.

8 FileNames Gets the file names of all selected files in the dialog box.

9 Filter Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

10 FilterInde x Gets or sets the index of the filter currently selected in the file dialog box.

11 InitialDirectory Gets or sets the initial directory displayed by the file dialog box.

12 OverwritePrompt Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already exists.

13 RestoreDirectory Gets or sets a value indicating whether the dialog box restores the current directory before closing.

14 ShowHelp Gets or sets a value indicating whether the Help button is displayed in the file dialog box.

15 SupportMultiDottedExtensions Gets or sets whether the dialog box supports displaying and saving files that have multiple file name extensions.

16 Title Gets or sets the file dialog box title.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 15

16 ValidateNames Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names.

Methods of the SaveFileDialog Control The following are some of the commonly used methods of the SaveFileDialog control:

S.N Method Name & Description

1 OpenFile Opens the file with read/write permission.

2 Reset Resets all dialog box options to their default values.

Example In this example, let's save the text entered into a rich text box by the user, using the save file dialog box. Take the following steps:

1. Drag and drop a Label control, a RichTextBox control, a Button control and a SaveFileDialog control on the form. 2. Set the Text property of the label and the button control to 'We appreciate your comments' and 'Save Comments' respectively. 3. Double-click the Save Comments button and modify the code of the Click event as shown:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt" If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _ Then My.Computer.FileSystem.WriteAllText _ (SaveFileDialog1.FileName, RichTextBox1.Text, True) End If End Sub

When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 16

We have set the Filter property of the SaveFileDialog control to display text file types with .txt extensions only.

Write some text in the text box and click on the Save Comment button to save the text as a text file in your computer.

PrintDialog Control The PrintDialog control lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application.

There are various other controls related to printing of documents. Let us have a brief look at these controls and their purpose. These other controls are:

• The PrintDocument control - it provides support for actual events and operations of printing in Visual Basic and sets the properties for printing. • The PrinterSettings control - it is used to configure how a document is printed by specifying the printer. • The PageSetUpDialog control - it allows the user to specify page-related print settings including page orientation, paper size and margin size. • The PrintPreviewControl control - it represents the raw preview part of print previewing from a Windows Forms application, without any dialog boxes or buttons. • The PrintPreviewDialog control - it represents a dialog box form that contains a PrintPreviewControl for printing from a Windows Forms application.

Following is the Print dialog box:

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 17

Properties of the PrintDialog Control

The following are some of the commonly used properties of the PrintDialog control:

S.N Property Description

1 AllowCurrentPage Gets or sets a value indicating whether the Current Page option button is displayed.

2 AllowPrintToFile Gets or sets a value indicating whether the Print to file check box is enabled.

3 AllowSelection Gets or sets a value indicating whether the Selection option button is enabled.

4 AllowSomePages Gets or sets a value indicating whether the Pages option button is enabled.

5 Document Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings.

6 PrinterSettings Gets or sets the printer settings the dialog box modifies.

7 PrintToFile Gets or sets a value indicating whether the Print to file check box is selected.

8 ShowHelp Gets or sets a value indicating whether the Help button is displayed.

9 ShowNetwork Gets or sets a value indicating whether the Network button is displayed.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 18

Methods of the PrintDialog Control

The following are some of the commonly used methods of the PrintDialog control:

S.N Method Name & Description

1 Reset Resets all options to their default values.

2 RunDialog When overridden in a derived class, specifies a common dialog box.

3 ShowDialog Runs a common dialog box with a default owner.

Example In this example, let us see how to show a Print dialog box in a form. Take the following steps:

• Add a PrintDocument control, a PrintDialog control and a Button control on the form. The PrintDocument and the PrintDialog controls are found on the Print category of the controls toolbox. • Change the text of the button to 'Print'. • Double-click the Print button and modify the code of the Click event as shown:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click PrintDialog1.Document = PrintDocument1 PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings PrintDialog1.AllowSomePages = True If PrintDialog1.ShowDialog = DialogResult.OK Then PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings PrintDocument1.Print() End If End Sub

When the application is compiled and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 19

Click the Print button to make the Print dialog box appear.

Multiple Document Interface (MDI) MDI is a popular interface because it allows you to have multiple documents (or forms) open in one application. Examples of MDI applications include Microsoft Word, Microsoft Excel, Microsoft PowerPoint, and even the Visual Studio integrated development environment itself. Each application consists of one (or more) parent windows, each containing an MDI client area—the area where the child forms (or documents) will be displayed.

Single Document Interface MDI is only one of several possible paradigms for creating a user interface. You can also create applications that display just a single form. They're easier to create, in fact. Those applications are called Single Document Interface (SDI) applications. Microsoft Windows Notepad is an SDI application, and you can only open a single document at a time.

Uses of MDI • You'll use MDI most often in applications where the user might like to have multiple forms or documents open concurrently. • Word processing applications (like Microsoft Word), spreadsheet applications (like Microsoft Excel), and project manager applications (like Microsoft Project) are all good candidates for MDI applications. • MDI is also handy when you have a large application, and you want to provide a simple mechanism for closing all the child forms when the user exits the application.

Creating an MDI Parent Form To create an MDI parent form, you can simply take one of your existing forms and set its IsMDIContainer property to True . This form will now be able to contain other forms as child forms. You may have one or many container forms within your application.

You may have as many different child forms (the forms that remain contained within the parent form) as you want in your project. A child form is nothing more than a regular form for which you dynamically set the MdiParent property to refer to the MDI container form.

Working with MDI Child Forms If you have multiple child forms open, you may want to have them arrange themselves, much as you can do in Word or Excel, choosing options under the Window menu. Table 3 lists the available options when arranging child windows.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 20

Table 3. Choose one of these values when arranging child windows

Menu Item Enumerated Value

Tile Horizontal MdlLayout.TileHorizontal

Tile Vertical MdiLayout.TileVertical

Cascade MdiLayout.Cascade

Arrange Icons MdiLayout.ArrangeIcons

MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and then returns an integer indicating which button the user clicked.

Syntax MsgBox(Prompt,[ Buttons , Title ] ) As MsgBoxResult

Parameters • Prompt - Required. String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately 1024 characters. • Buttons - Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If you omit Buttons, the default value is zero. • Title - Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the title bar.

The MsgBoxStyle enumeration values are listed in the following table.

Member Value Description

OKOnly 0 Displays OK button only.

OKCancel 1 Displays OK and Cancel buttons.

AbortRetryIgnore 2 Displays Abort, Retry, and Ignore buttons.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 21

YesNoCancel 3 Displays Yes, No, and Cancel buttons.

YesNo 4 Displays Yes and No buttons.

RetryCancel 5 Displays Retry and Cancel buttons.

Critical 16 Displays Critical Message icon.

Question 32 Displays Warning Query icon.

Exclamation 48 Displays Warning Message icon.

Information 64 Displays Information Message icon.

DefaultButton1 0 First button is default.

DefaultButton2 256 Second button is default.

DefaultButton3 512 Third button is default.

ApplicationModal 0 Application is modal. The user must respond to the message box before continuing work in the current application.

SystemModal 4096 System is modal. All applications are suspended until the user responds to the message box.

MsgBoxSetForeground 65536 Specifies the message box window as the foreground window.

MsgBoxRight 524288 Text is right -aligned.

MsgBoxRtlReading 1048576 Specifies text shou ld appear as right -to -left reading on Hebrew and Arabic systems.

The first group of values (0–5) describes the number and type of buttons displayed in the dialog box. The second group (16, 32, 48, 64) describes the icon style. The third group (0, 256, 512) determines which button is the default. The fourth group (0, 4096) determines the modality of the message box, and the fifth group specifies whether or not the message box window is the foreground window, along with the alignment and direction of the text. When adding numbers to create a final value for the Buttons argument, use only one number from each group.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 22

Return Value

Constant Value

OK 1

Cancel 2

Abort 3

Retry 4

Ignore 5

Yes 6

No 7

Example:

Dim msg As String Dim title As String Dim style As MsgBoxStyle Dim response As MsgBoxResult msg = "Do you want to continue?" ' Define message. style = MsgBoxStyle.DefaultButton2 Or _ MsgBoxStyle.Critical Or MsgBoxStyle.YesNo title = "MsgBox Demonstration" ' Define title. ' Display message. response = MsgBox(msg, style, title) If response = MsgBoxResult.Yes Then ' User chose Yes. ' Perform some action. Else ' Perform some other action. End If

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 23

InputBox Function Displays a prompt in a dialog box, waits for the user to input text or click a button, and then returns a string containing the contents of the text box.

Syntax: InputBox( Prompt, [ Title ,DefaultResponse, Xpos , YPos ] ) As String

Parameters • Prompt - Required String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately 1024 characters, depending on the width of the characters used. • Title - Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the title bar. • DefaultResponse - Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit DefaultResponse, the displayed text box is empty. • XPos - Optional. Numeric expression that specifies, in pixels, the distance of the left edge of the dialog box from the left edge of the screen. If you omit XPos and YPos, the dialog box is centered on the screen. • YPos -Optional. Numeric expression that specifies, in pixels, the distance of the upper edge of the dialog box from the top of the screen. If you omit XPos and YPos, the dialog box is centered on the screen.

Example:

Dim message, title, defaultValue As String Dim myValue As Object ' Set prompt. message = "Enter a value between 1 and 3" ' Set title. title = "InputBox Demo" defaultValue = "1" ' Set default value.

' Display message, title, and default value. myValue = InputBox(message, title, defaultValue) ' If user has clicked Cancel, set myValue to defaultValue If myValue Is "" Then myValue = defaultValue

' Display dialog box at position 100, 100.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 24

myValue = InputBox(message, title, defaultValue, 100, 100) ' If user has clicked Cancel, set myValue to defaultValue If myValue Is "" Then myValue = defaultValue

BUILT-IN FUNCTIONS

String Functions The following table lists the functions that Visual Basic provides to search and manipulate strings.

.NET Framework Description method

Asc Returns an Integer value representing the character code corresponding to a character.

Chr Returns the character associated with the specified character code.

Format Returns a string formatted according to instructions contained in a format String expression.

InStr Returns an integer specifying the start po sition of the first occurrence of one string within another.

InStrRev Returns the position of the first occurrence of one string within another, starting from the right side of the string.

Join Returns a string created by joining a number of substrings contained in an array.

LCase Returns a string or character converted to lowercase.

Len Returns an integer that contains the number of characters in a string.

LTrim Returns a string containing a copy of a specified string with no leading spaces.

Replace Returns a string in which a specified substring has been replaced with another substring a specified number of times.

RTrim Returns a string containing a copy of a specified string with no trailing spaces.

Split Returns a zero -based, one -dimen sional array containing a specified number of substrings.

StrComp Returns -1, 0, or 1, based on the result of a string comparison.

StrDup Returns a string or object consisting of the specified character repeated the

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 25

specified number of times.

StrReverse Returns a string in which the character order of a specified string is reversed.

Trim Returns a string containing a copy of a specified string with no leading or trailing spaces.

UCase Returns a string or character containing the specified string converted to uppercase.

Example - This example defines all the above function. Module Module1 Sub Main() Dim leng As String = Len( " Rohatash kumar" ) Console .WriteLine( "length is :" & leng) Dim middle As String = Mid( "Rohatash Kumar" , 3, 4) Console .WriteLine( "Mid is :" & middle) Dim leftf As String = Left( "Rohatash Kumar" , 3) Console .WriteLine( "Left is:" & leftf) Dim rightr As String = Right( "rohatash kumar" , 6) Console .WriteLine( "Right is :" & rightr) Dim spaces As String = Right( "rohatash kumar" , 7) Console .WriteLine( "Space is :" & spaces) Dim replaces As String = Replace( "rohatash kumar" , "hat" , "nmo" ) Console .WriteLine( "Replace is :" & replaces) Dim trimt As String = Trim( " rohatash kumar ") Console .WriteLine( "Trim is :" & trimt) Dim ltriml As String = LTrim( " rohatash kumar ") Console .WriteLine( "ltrim is :" & ltriml) Dim rtrimr As String = RTrim( " rohatash kumar ") Console .WriteLine( "rtrim is :" & rtrimr) Dim ucaseu As String = UCase( "rohatash kumar" ) Console .WriteLine( "Ucase is :" & ucaseu) Dim lcasel As String = LCase( "ROHATASH KUMAR" ) Console .WriteLine( "Ucase is :" & lcasel) End Sub End Module

Math Functions The methods of the System.Math class provide trigonometric, logarithmic, and other common mathematical functions. To use these functions without qualification, import the System.Math namespace into your project by adding the following code to the top of your source file:

Imports System.Math

The following table lists methods of the System.Math class. You can use these in a Visual Basic program.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 26

.NET Framework Description method

Abs Returns the absolute value of a number.

Acos Returns the angle whose cosine is the specified number.

Asin Returns the angle whose sine is the specified number.

Atan Returns the angle whose tangent is the specified number.

Atan2 Returns the angle whose tangent is the quotient of two specified numbers.

BigMul Returns the full product of two 32 -bit numbers.

Ceiling Returns the smallest integral value that's greater than or equal to the specified Decimal or Double.

Cos Returns the cosine of the specified angle.

Cosh Returns the hyperbolic cosine of the specified angle.

DivRem Returns the quotient of two 32 -bit or 64 -bit signed integers, and also returns the remainder in an output parameter.

Exp Returns e (the base of natural logarithms) raised to the specified power.

Floor Returns the largest integer that's less than or equal to the speci fied Decimal or Double number.

Log Returns the natural (base e) logarithm of a specified number or the logarithm of a specified number in a specified base.

Log10 Returns the base 10 logarithm of a specified number.

Max Returns the larger of two numbers.

Min Returns the smaller of two numbers.

Pow Returns a specified number raised to the specified power.

Round Returns a Decimal or Double value rounded to the nearest integral value or to a specified number of fractional digits.

Sign Returns an Integer value indicating the sign of a number.

Sin Returns the sine of the specified angle.

Sinh Returns the hyperbolic sine of the specified angle.

Sqrt Returns the square root of a specified number.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 27

Tan Returns the tangent of the specified angle.

Tanh Returns the hyperbolic tangent of the specified angle.

Truncate Calculates the integral part of a specified Decimal or Double number.

Example Imports System. Math Module Module1 Sub Main() WriteLine( "Tan 90 is" & " " & Tan(90)) 'display Tan90 value WriteLine( "Square root of 121 is " & " " & Sqrt(121)) 'displays square root of 121 WriteLine( "Log value of 15 is" & " " & Log(15)) 'displays the logarithm value of 15 Read() End Sub End Module

Financial Functions Visual Basic .NET is equipped with a good number of powerful financial functions so that you can comfortably use this programming language to build software for banks, share markets, and various other challenging financial applications. These functions have been listed below table and each is accompanied by a brief description.

Function Description DDB () Returns the depreciation of an asset for a specific time period using the Double -Declining Balance method.

FV () Returns the Future Value of an annuity based on fixed periodic payments and a fixed interest rate.

IPmt () Returns the Interest Pay men t for a given period of an annuity based on fixed periodic payments and a fixed interest rate.

IRR () Returns the Internal Rate of Return for a series of periodic cash flows (payments and receipts).

MIRR () Returns the Modified Internal Rate of Return for a series of periodic cash flows (payments and receipts).

NPer () Returns the Number of Per iods for an annuity based on fixed periodic payments and a fixed interest rate.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 28

NPV () Returns Net Present Value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate.

PMT () Returns the Pay Men T for an annuity based on fixed periodic payments and a fixed interest rate.

PPMT () Returns the Principal Pay Men T for a given period of an annuity based on fixed periodic payments and a fixed interest rate.

PV () Returns the Present Value of an annuity based on fixed periodic payments to be paid in the future and a fixed interest rate.

Rate () Returns the interest Rate per period for an annuity.

SLN () Returns the Straigh t-LiNe depreciation of an asset for a single period.

SYD () Returns the Sum -of -Years Digits depreciation of an asset for a specified period.

Date and Time Handling Functions Date and time handling functions are very useful in real-time systems. Visual Basic .NET can handle all the dates between 1st January, 100 to 31st December, 9999, which covers a comfortable span of 9900 years. These functions are very important for banks and other similar organizations, where computation of interest on loans and deposits is calculated by using the concerned dates. Table A below enlists some of the date and time functions available in Visual Basic .NET.

Table A: Dates and Time handling functions

To do this Use this

Get the current date or time Today, Now, TimeofDay, DateString, TimeString

Perform date calculations DateAdd, DateDiff, DatePart

Return a date DateSerial, DateValue

Return a time TimeSerial, TimeValue

Set the date or time Today, TimeofDay

Time a process Timer

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 29

Example:

Imports System.Math Module Module1 Sub Main() Dim FirstDate As Date FirstDate = #12/31/2001# System.Console.WriteLine("New date: " & DateAdd_ (DateInterval.Month, 22, FirstDate)) End Sub End Module

There's something else you should know-the Format function makes it easy to format dates into strings, including times. For easy reference, see Table 2.11, which shows some ways to display the date and time in a string-note how many ways there are to do this.

Table B: Using Format to display dates and times.

Format Expression Yields this

Format(Now, "M -d-yy") "1 -1-03"

Format(Now, "M/d/yy") "1/1/03"

Format(Now, "MM - dd - yy") "01 /01 / 03"

Format(Now, "ddd, MMMM d, yyy") "Friday, January 1, 2003"

Format(Now, "d MMM, yyy") "1 Jan, 2003"

Format(Now, "hh:mm:ss MM/dd/yy") "01:00:00 01/01/03"

Format(Now, "hh:mm:ss tt MM -dd -yy") "01:00:00 AM 01 -01 -03"

Sub Procedures and Functions Procedures are made up of series of Visual Basic statements that, when called, are executed. After the call is finished, control returns to the statement that called the procedure. In this way, procedures make it simple for the programmer to package your code into discrete units. Ideally, each Visual Basic procedure should handle one—and only one—task, to make this easy to remember. There are two types of procedures in Visual Basic .NET: Sub procedures and functions. Sub procedures do not return a value, while functions do.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 30

Sub Procedures A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub , Exit Sub , or Return statement encountered.

A Sub procedure performs actions but does not return a value. It can take arguments, such as constants, variables, or expressions, that are passed to it by the calling code.

The syntax for declaring a Sub procedure is as follows:

[accessibility] Sub subname[(argumentlist)]

' Statements of the Sub procedure go here.

End Sub

The accessibility can be Public, Protected, Friend, Protected Friend , or Private.

You can define Sub procedures in modules, classes, and structures. They are Public by default, which means you can call them from anywhere in your application.

Argument Declaration You declare each argument for a procedure the same way you declare a variable, specifying the argument name and data type. You can also specify the passing mechanism, and whether the argument is optional.

The syntax for each argument in the argument list is as follows:

[Optional] [ByVal|ByRef] [ParamArray] argumentname As datatype

If the argument is optional, you must also supply a default value in its declaration, as follows:

Optional [ByVal|ByRef] argumentname As datatype = defaultvalue

Calling Syntax You invoke a Sub procedure explicitly with a stand-alone calling statement. You cannot call it by using its name within an expression. The calling statement must provide values for all arguments that are not optional, and it must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional also.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 31

The syntax for a call to a Sub procedure is as follows:

[Call] subname[(argumentlist)]

Example: The following Sub procedure tells the computer operator which task the application is about to perform, and also displays a time stamp. Instead of duplicating this code at the beginning of every task, the application simply calls TellOperator from various places. Each call passes a string in the

Task argument that identifies the task being started.

Sub TellOperator(ByVal Task As String) Dim Stamp As Date ' Stamp is local to TellOperator. Stamp = TimeOfDay() ' Get current time for time stamp. ' Use MessageBox class of System.Windows.Forms namespace. MessageBox.Show("Starting " & Task & " at " & CStr(Stamp)) End Sub

A typical call to TellOperator is as follows:

Call TellOperator("file update")

Function Procedures A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. Each time the procedure is called, its statements are executed, starting with the first executable statement after the Function statement and ending with the first End Function , Exit Function , or Return statement encountered.

A Function procedure is similar to a Sub procedure, but it also returns a value to the calling program. A Function procedure can take arguments passed to it by the calling code, such as constants, variables, or expressions.

The syntax for declaring a Function procedure is as follows:

[accessibility] Function functionname[(argumentlist)] As datatype ' Statements of the Function procedure. End Function

The accessibility can be Public, Protected, Friend, Protected Friend , or Private.

You can define Function procedures in modules, classes, and structures. They are Public by default, which means you can call them from anywhere in your application.

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 32

You declare each argument the same as you do for a Sub procedure.

Return Values The value a Function procedure sends back to the calling program is called its return value . The function returns the value in one of two ways:

• It assigns a value to its own function name in one or more statements of the procedure. Control is not returned to the calling program until an Exit Function or End Function statement is executed, as in the following example:

Function functionname[(argumentlist)] As datatype ' ... functionname = expression 'Control remains within the function. ' ... End Function

• It uses the Return statement to specify the return value, and returns control immediately to the calling program, as in the following example:

Function functionname[(argumentlist)] As datatype ' ... Return expression 'Control is returned immediately. ' ... End Function

The advantage of assigning the return value to the function name is that control does not return from the function until the program encounters an Exit Function or End Function statement. This allows you to assign a preliminary value and adjust it later if necessary.

If the function returns an array data type, you cannot access the individual elements of the array within the function. If you attempt to do this, the compiler interprets it as a call to the function. The following example generates compiler errors:

Function AllOnes(ByVal N As Integer) As Integer() Dim I As Integer ' Singleton Integer, not Integer array. For I = 1 To N - 1 ' Assume N has a valid value. AllOnes(I) = 1 ' Compiler error: call with wrong data type. Next I Return AllOnes() ' Compiler error: call with no argument. End Function

Prof. Sushant S. Sundikar VB.NET Unit4: Functions, Built-In Dialog Boxes, Menus and Toolbar 33

Every Function procedure has a data type, just as every variable does. This data type is specified by the As clause in the Function statement, and it determines the type of the return value. The following sample declarations illustrate this:

Function Yesterday As Date ' ... End Function Function FindSqrt(ByVal Number As Single) As Single ' ... End Function

Calling Syntax You call a Function procedure by including its name and arguments either on the right side of an assignment statement or in an expression. The following sample calls illustrate this:

lvalue = functionname[(argumentlist)] If ((functionname[(argumentlist)] / 3) <= expression) Then

Example: The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides:

Function Hypotenuse (ByVal Side1 As Single, ByVal Side2 As Single) As Single

Return Math.Sqrt((Side1 ^ 2) + (Side2 ^ 2))

End Function

Typical calls to Hypotenuse are as follows:

Dim TestLength, TestHypotenuse, X, Y, Area As Single

TestHypotenuse = Hypotenuse(TestLength, 10.7)

' Assume TriangleArea is a defined Function procedure — the

' returned value from Hypotenuse is used as an argument to TriangleArea.

Area = TriangleArea(X, Y, Hypotenuse(X, Y))

Prof. Sushant S. Sundikar VB.NET