Sunteți pe pagina 1din 42

C H A P T E R

2
Windows Forms Controls - II
In this Chapter:

Using the ToolStrip Control Using the MenuStrip Control Using the StatusStrip Control Working with Dialog Boxes

62 Comdex .NET 4.0 Programming Course Kit


There may be situations when you need to provide several options for performing different sets of tasks to the users of your Windows Forms application. Some of these options may be related to one another, which implies that you can group them together. You can opt to use the RadioButton, CheckBox, and ListBox controls to present these options to the users; however, these controls occupy a lot of space on the User Interface (UI) of a Windows Forms application. In such cases, you can use the ToolStrip and MenuStrip controls to provide tool strips and menus in a Windows Forms application. Tool strips and menus offer an easy, convenient, and compact means of logically grouping numerous options. You can also display information about other controls by using a status strip provided by the StatusStrip control. Visual C# 2010 also offers various built-in dialog boxes, which refer to windows that contain various options to perform a task. Some of the built-in dialog boxes include the Browse For Folder, Open, and Save As dialog boxes. These dialog boxes allow you to perform some common tasks, such as browsing through folders, opening files, and deleting a folder. The FolderBrowserDialog, OpenFileDialog, and SaveFileDialog controls in Visual C# 2010 offer the functionality to work with the Browse For Folder, Open, and Save As dialog boxes, respectively. Visual C# 2010 also offers the functionality to work with the Font and Color dialog boxes through the FontDialog and ColorDialog controls. The Print dialog box is also supported in Visual C# 2010 and is offered by the PrintDialog and PrintDocument controls. In this chapter, you learn about tool strips, menus, and status strips in Visual C# 2010 through the ToolStrip, MenuStrip, and StatusStrip controls, respectively. You also learn about the FolderBrowserDialog, OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDialog, and PrintDocument controls that allow you to work with the Browse For Folder, Open, Save As, Font, Color, and Print dialog boxes. Lets begin by discussing the ToolStrip control.

Using the ToolStrip Control


The ToolStrip control offers a strip of tools or controls (also called tool strip items) that correspond to the common options, such as layout options and frequently performed tasks, such as saving and opening files. With the ToolStrip control, you can design your Windows Forms application with a rich yet compact UI, provide users a quick way to select the desired options, and perform the required tasks. The ToolStrip class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the ToolStrip control. Table 2.1 lists the noteworthy properties of the ToolStrip class: Table 2.1: Noteworthy Properties of the ToolStrip Class Property
AutoSize ImageList IsDropDown Items LayoutStyle Orientation ShowItem ToolTips Stretch

Description
Returns or sets a value that indicates whether the ToolStrip control is automatically resized to display its entire content or not Returns or sets the image list that contains the images displayed on a tool strip item Returns a value that indicates whether the ToolStrip control appears as a drop-down list or not Returns all the items (such as buttons, text boxes, and labels) of the ToolStrip control Returns or sets a value that indicates the way the ToolStrip control places its items Returns the orientation of the ToolStripPanel object Returns or sets a value that indicates whether ToolTips for the tool strip items are displayed or not Returns or sets a value that indicates whether the ToolStrip control stretches from one end to another end in the ToolStripContainer control

Windows Forms Controls - II 63


Table 2.1: Noteworthy Properties of the ToolStrip Class Property
TabStop TextDirection

Description
Returns or sets a value indicating whether the user can give focus to a tool strip item by using the TAB key Returns or sets the direction in which the text on the ToolStrip control appears

Table 2.2 lists the noteworthy methods of the ToolStrip class: Table 2.2: Noteworthy Methods of the ToolStrip Class Method
GetItemAt GetNextItem

Description
Returns the tool strip item at a given location Returns the next tool strip item from a given reference point and moves in a specific direction

Table 2.3 lists the noteworthy events of the ToolStrip class: Table 2.3: Noteworthy Events of the ToolStrip Class Event
AutoSizeChanged ItemAdded ItemClicked ItemRemoved LayoutStyleChanged

Description
Occurs when the AutoSize property changes Occurs when a new item is added to the ToolStrip control Occurs when a tool strip item is clicked Occurs when a tool strip item is removed from the ToolStrip control Occurs when the LayoutStyle property changes

The ToolStrip control contains the following types of controls that are referred as tool strip items:

ToolStripButton: Represents a button that can contain text and/or image ToolStripLabel: Represents a label that can contain text, image, or hyperlink ToolStripTextBox: Represents a text box in which users can enter text ToolStripComboBox: Represents a combo box ToolStripSeparator: Represents a vertical line that logically groups the tool strip items ToolStripDropDownButton: Represents a button that displays a drop-down list ToolStripSplitButton: Represents a combination of a standard button, which is on the left-hand side and a drop-down button, which is on the right-hand side ToolStripProgressBar: Represents a progress bar The tool strip items are objects of the ToolStripItem class, which exists in the System.Windows.Forms namespace. The individual tool strip items are objects of the derived classes of the ToolStripItem class.

All the tool strip items have certain common properties, methods, and events. Table 2.4 lists noteworthy common properties of the tool strip items: Table 2.4: Noteworthy Common Properties of the Tool Strip Items Property
Alignment AutoSize

Description
Returns or sets a value that signifies whether the item aligns towards the start or the end of the ToolStrip control Returns or sets a value that indicates whether the item is automatically resized

64 Comdex .NET 4.0 Programming Course Kit


Table 2.4: Noteworthy Common Properties of the Tool Strip Items Property
AutoToolTip CanSelect DisplayStyle Image Name Text TextDirection ToolTipText Visible

Description
Returns or sets a value that indicates whether to use the Text property or the ToolTipText property for the tooltip of the tool strip item Returns a value that indicates whether the tool strip item can be selected Returns or sets whether the text and/or images are displayed on a tool strip item Returns or sets the image displayed on a tool strip item Returns or sets the name of the tool strip item Returns or sets the text that appears on the tool strip item Returns the orientation of the text used on the tool strip item Returns or sets the text that appears as a tooltip Returns or sets a value that indicates whether the item is visible or hidden

Table 2.5 lists noteworthy common methods of the tool strip items: Table 2.5: Noteworthy Common Methods of the Tool Strip Items Method
GetCurrentParent PerformClick Select

Description
Returns a ToolStrip control that contains the tool strip item Activates the tool strip item when its Click event occurs Selects the tool strip item

Table 2.6 lists noteworthy common events of the tool strip items: Table 2.6: Noteworthy Common Events of the Tool Strip Items Event
Click DisplayStyleChanged TextChanged

Description
Occurs when a user clicks the tool strip item Occurs when there is a change in the value of the DisplayStyle property Occurs when the Text property of the tool strip item changes

Perform the following steps to use the ToolStrip control in a Windows Forms application: 1. 2. 3. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyToolStrip (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyToolStrip application is created (Fig.C#-2.1). Drag and drop a ToolStrip control on the form from the Menus & Toolbars tab of the Toolbox. The ToolStrip control is added to the form as well as to the component tray (Fig.C#-2.1). You can notice in Fig.C#-2.1 that by default, the ToolStrip control does not have any tool strip items. In the subsequent steps, we add items to the ToolStrip control.

4. 5. 6. 7.

Windows Forms Controls - II 65


8. Select the ToolStrip control in the form, select the Items property of the ToolStrip control in the Properties window, and click the ellipsis button () in front of this property, as shown in Fig.C#-2.1:

Fig.C#-2.1 The Items Collection Editor dialog box opens, as shown in Fig.C#-2.2:

Fig.C#-2.2 You can notice in Fig.C#-2.2 that the Members list box of the Items Collection Editor dialog box displays only the ToolStrip control, ToolStrip1, which implies that the ToolStrip control contains no items. The items, such as button, text box, label, combo box, drop-down button, and split button, can be added to the ToolStrip control by using the Items Collection Editor dialog box. You can also set the properties of the tool strip items by using the Items Collection Editor dialog box. Select an item that you want to add to the ToolStrip control from the Select item and add to list below: drop-down list. In our case, we have selected the Label control, as shown in Fig.C#-2.3:

9.

10

Fig.C#-2.3

66 Comdex .NET 4.0 Programming Course Kit


10. Click the Add button to add the selected tool strip item to the ToolStrip control (Fig.C#-2.3). The selected item appears (ToolStripLabel1) under the ToolStrip control, ToolStrip1, in the Members list box of the Items Collection Editor dialog box (Fig.C#-2.4). 11. Repeat Step 9 and 10 to add as many items as you want to the ToolStrip control (Fig.C#-2.4). In our case, we have added two more tool strip items, ToolStripTextBox1 and ToolStripButton1, to the ToolStrip control. Now, you can also set various properties of the tool strip items added to the ToolStrip control by first selecting an item from the Members list box and then setting its value in the right pane of the Items Collection Editor dialog box. 12. Set the Text properties of ToolStripLabel1 and ToolStripTextBox1 to MyToolStrip and Enter Text, respectively. 13. Set the Text and DisplayStyle properties of ToolStripButton1 to Add File and ImageAndText, respectively. 14. Click the OK button to close the Items Collection Editor dialog box, as shown in Fig.C#-2.4:

14
Fig.C#-2.4 The ToolStrip control appears with the added items on the form, as shown in Fig.C#-2.5:

Fig.C#-2.5 15. Double-click the ToolStrip control in the form and add the highlighted line of code, as shown in Listing 2.1, to the Code Editor: Listing 2.1: Showing the Code to Handle the ItemClicked Event of the ToolStrip Control
private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { MessageBox.Show("You clicked: " + e.ClickedItem.Name); }

Windows Forms Controls - II 67


Listing 2.1 shows the code for the event handler of the ItemClicked event of the ToolStrip control. This event handler executes when you click a tool strip item of ToolStrip1. A message box will appear displaying a message indicating the name of the tool strip item that you click. 16. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.6). 17. Click the Add File button on the ToolStrip control, as shown in Fig.C#-2.6:

17

Fig.C#-2.6 A message box appears displaying the message, You clicked: ToolStripButton1 (Fig.C#-2.7). 18. Click the OK button to close the message box, as shown in Fig.C#-2.7:

18
Fig.C#-2.7 You have learned to work with the ToolStrip control. In the next section, you learn to work with the MenuStrip control.

Using the MenuStrip Control


While working with Visual Studio 2010 Integrated Development Environment (IDE), you must have used the menu bar and its various menus several times. Similar to the menu bar of Visual Studio 2010 IDE, you can also design a menu bar for your own Windows Forms application to logically group commonly used options that can be selected by the user. You can add a menu bar to the Windows Forms application by using the MenuStrip control. The MenuStrip control acts as a container for a single menu bar on a Windows form. You can add several menus containing logically grouped menu items to a menu bar. The menu items represent options that can be selected by the user and contain submenus, which are menus with different sets of options. The MenuStrip class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the MenuStrip control. Table 2.7 lists the noteworthy properties of the MenuStrip class: Table 2.7: Noteworthy Properties of the MenuStrip Class Property
CanOverflow ShowItemToolTips Stretch

Description
Returns or sets a value that indicates whether the MenuStrip control supports overflow functionality Returns or sets a value that indicates whether tooltips appear for the MenuStrip control Returns or sets a value that indicates whether the MenuStrip control stretches from one end to another end in its container

68 Comdex .NET 4.0 Programming Course Kit


Table 2.8 lists the noteworthy events of the MenuStrip class: Table 2.8: Noteworthy Events of the MenuStrip Class Event
MenuActivate MenuDeactivate

Description
Occurs when the user accesses the menu Occurs when the MenuStrip control is deactivated

The MenuStrip control is only a container for the menus. After adding a MenuStrip control in a Windows Forms application, you need to add the menus and their menu items manually. You can also add separators to menu items, assign shortcut keys for menu and menu items, display check marks for menu items, and create submenus. You can also add access keys to menus and menu items. An access key is a character that you can use with the ALT key to access or select a menu or menu item. To specify an access key for a menu or menu item, you need to prefix the character, which you want to make the access key, with an ampersand (&) in the Text property of the menu or menu item. The access key appears underlined in the menu or menu item name. For example, if you specify the Text property of the File menu as &File, then f (or F) becomes the access key for the File menu. The menus and menu ToolStripMenuItem class. items are generally represented as objects of the

Some properties and events are common to the menus and menu items. Table 2.9 lists noteworthy common properties of the menus and menu items: Table 2.9: Noteworthy Common Properties of the Menus and Menu Items Property
Checked CheckOnClick CheckState Enabled ShortcutKeys ShowShortcutKeys

Description
Returns or sets a value that indicates whether the menu (or menu item) object is checked Returns or sets a value specifying whether the menu (or menu item) object automatically appears checked or unchecked when clicked Returns or sets a value that indicates whether the menu (or menu item) is in the checked, unchecked, or indeterminate state Returns or sets a value that indicates whether the menu (or menu item) is enabled Returns or sets the shortcut keys associated with the menu (or menu item) Returns or sets a value that indicates whether the shortcut keys associated with the menu (or menu item) are displayed next to it

Table 2.10 lists noteworthy common events of the menus and menu items: Table 2.10: Noteworthy Common Events of the Menus and Menu Items Event
CheckedChanged CheckStateChanged

Description
Occurs when the Checked property changes Occurs when the CheckState property changes

You can follow some conventions related to menus and menu items to make Windows Forms applications more user-friendly. These conventions are as follows:

If selecting a menu item opens a dialog box, then you can add an ellipsis (...) after the name of the menu item (for example, Print...). If a menu item performs a particular action immediately instead of opening a submenu, then you can append an exclamation point (!) to the name of the menu item (for example, Connect!).

Windows Forms Controls - II 69


You should place the File menu as the first menu with the Exit item as its last menu item. You should use separator lines to group logically related menu items together on the menu dropdrown list. Perform the following steps to use the MenuStrip control in a Windows Forms application:

1. 2. 3.

4. 5. 6. 7.

8.

Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyMenuStrip (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyMenuStrip application is created (Fig.C#-2.8). Drag and drop a MenuStrip control on the form from the Menus & Toolbars tab of the Toolbox. The MenuStrip control is added to the form as well as to the component tray (Fig.C#-2.8). In Fig.C#-2.8, the MenuStrip control displays a text box with the placeholder text, Type Here. You can type the name of a menu in the Type Here text box. Click inside the Type Here text box to specify the name of a menu, as shown in Fig.C#-2.8:

Fig.C#-2.8 The placeholder text in the text box disappears and two more text boxes, one on the right side of the text box and other under the text box, are displayed with the text, Type Here (Fig.C#-2.9). The text box on the right side of this text box allows you to add another menu and the text box under this text box allows you to add a menu item to the menu. Type the name of a menu in the text box. In our case, we have typed File, as shown in Fig.C#-2.9:

9.

70 Comdex .NET 4.0 Programming Course Kit

Fig.C#-2.9 10. Type the name of another menu in the text box available on the right side of the File menu to create another menu. In our case, we have typed Edit, as shown in Fig.C#-2.10:

10

Fig.C#-2.10 In Fig.C#-2.10, one text box appears to the right of the Edit menu and one text box appears under it similar to the File menu. You can use the text box appearing under the Edit menu to add new items. 11. Select the File menu and type the name of the first menu item for this menu in the text box displayed under this menu. In our case, we have specified New as the first menu item for the File menu, as shown in Fig.C#-2.11:

Windows Forms Controls - II 71

11

Fig.C#-2.11 12. Type the name of the second menu item for the File menu in the text box under the New menu item. In our case, we have specified Open as the second menu item for the File menu, as shown in Fig.C#-2.12:

12

Fig.C#-2.12 13. Type (hyphen) in the text box under the Open menu item for the File menu, as shown in Fig.C#-2.13:

72 Comdex .NET 4.0 Programming Course Kit

13

Fig.C#-2.13 14. Press the ENTER key on the keyboard. A separator is added under the Open menu item for the File menu, as shown in Fig.C#-2.14:

Fig.C#-2.14 15. Add as many items as you want to the first menu. In our case, we have added two more items, Save and Exit, to the File menu, as shown in Fig.C#-2.15:

Windows Forms Controls - II 73

Fig.C#-2.15 16. Add items to the Edit menu as you add items to the File menu. In our case, we have added three items, Cut, Copy, and Paste, to the Edit menu, as shown in Fig.C#-2.16:

Fig.C#-2.16 You have created menus and added menu items to the menus. In the subsequent steps, you learn to assign shortcut keys to menu items. 17. Select a menu item such as FileNew of a menu in the form, select the ShortcutKeys property of the menu item in the Properties window, and click the down arrow button in front of this property. A drop-down menu appears (Fig.C#-2.17). 18. Select the Ctrl check box under the Modifiers option (Fig.C#-2.17). 19. Click the drop-down list under the Key option, as shown in Fig.C#-2.17:

74 Comdex .NET 4.0 Programming Course Kit

17 18 19
Fig.C#-2.17 A drop-down list appears (Fig.C#-2.18). 20. Select a key from the drop-down list. In our case, we have selected N, as shown in Fig.C#-2.18:

20

Fig.C#-2.18 21. Press the ENTER key on the keyboard. The shortcut keys for the menu item are displayed next to it in the form, as shown in Fig.C#-2.19:

Windows Forms Controls - II 75

Fig.C#-2.19 22. Double-click the MenuStrip control in the form and add the highlighted line of code, as shown in Listing 2.2, to the Code Editor: Listing 2.2: Showing the Code to Handle the ItemClicked Event of the MenuStrip Control
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { MessageBox.Show("You clicked: " + e.ClickedItem.Name); }

Listing 2.2 shows the code for the event handler of the ItemClicked event of the MenuStrip control. This event handler executes when you click a menu item of MenuStrip1. A message box appears displaying a message indicating the name of the menu item that you click. 23. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.20). 24. Select the File menu (Fig.C#-2.20). A message box appears displaying the message, You clicked: FileToolStripMenuItem, as shown in Fig.C#-2.20:

24

25
Fig.C#-2.20 25. Click the OK button to close the message box (Fig.C#-2.20). 26. Select the Edit menu (Fig.C#-2.21). A message box appears displaying the message, You clicked: EditToolStripMenuItem (Fig.C#-2.21). 27. Click the OK button to close the message box, as shown in Fig.C#-2.21:

76 Comdex .NET 4.0 Programming Course Kit


26

27
Fig.C#-2.21 Lets now learn about the StatusStrip control.

Using the StatusStrip Control


The StatusStrip control allows you to display a variety of information, such as the name or description of another control, the progress of an ongoing task, and the instructions for users to perform a particular task. The StatusStrip class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the StatusStrip control. Table 2.11 lists the noteworthy properties of the StatusStrip class: Table 2.11: Noteworthy Properties of the StatusStrip Class Property
Dock LayoutStyle ShowItemToolTips SizingGrip Stretch

Description
Returns or sets the borders of the StatusStrip control that are docked to its parent control Returns or sets a value that indicates the way in which the items in the StatusStrip control are placed in it Returns or sets a value that indicates whether the ToolTips are displayed for the StatusStrip control Returns or sets a value that indicates whether a handle for sizing the StatusStrip control appears in its lower-right corner Returns or sets a value that indicates whether the StatusStrip control stretches from one end to another in its container

The StatusStrip control can contain several controls or items, which are as follows: ToolStripStatusLabel: Represents a label in the StatusStrip control ToolStripDropDownButtton: Represents a drop-down button that when clicked displays a dropdown list ToolStripSplitButton: Represents a split button (combination of a standard button on the left and a drop-down button on the right) ToolStripProgressBar: Represents a progress bar Perform the following steps to use the StatusStrip control in a Windows Forms application:

1. 2. 3.

4. 5.

Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyStatusStrip (also available on the CD) in the Name text box and an appropriate location for the application in the Location box.

Windows Forms Controls - II 77


Click the OK button to close the New Project dialog box. The MyStatusStrip application is created (Fig.C#-2.22). 7. Drag and drop a Label control and a TextBox control on the form from the Toolbox. 8. Select the Label control in the form and set its Text property to Enter text: in the Properties window. 9. Select the TextBox control in the form, then set its Multiline property to True in the Properties window, and then resize it to accommodate multiple lines of text. 10. Drag and drop a StatusStrip control on the form from the Menus & Toolbars tab of the Toolbox. The StatusStrip control is added to both the bottom of the form and the component tray (Fig.C#-2.22). You can notice in Fig.C#-2.22 that by default, the StatusStrip control does not have any items. In the subsequent steps, we add items to the StatusStrip control. 11. Select the StatusStrip control in the form, select the Items property of the StatusStrip control in the Properties window, and click the ellipsis button () in front of this property, as shown in Fig.C#-2.22: 6.

11

Fig.C#-2.22 The Items Collection Editor dialog box opens (Fig.C#-2.23) 12. Select the StatusLabel option from the Select item and add to list below: drop-down list, as shown in Fig.C#-2.23:

12

13

Fig.C#-2.23 13. Click the Add button (Fig.C#-2.23). A control corresponding to the StatusLabel option, ToolStripStatusLabel1, is added under the StatusStrip control, StatusStrip1, in the Members list box (Fig.C#-2.24). 14. Select the DropDownButton option from the Select item and add to list below: drop-down list (Fig.C#-2.24). 15. Click the Add button to add the selected option, as shown in Fig.C#-2.24:

78 Comdex .NET 4.0 Programming Course Kit


14 15

Fig.C#-2.24 A control corresponding to the DropDownButton option, ToolStripDropDownButton1, is added under the StatusStrip1 node in the Members list box (Fig.C#-2.25). 16. Select the ToolStripDropDownButton1 node from the Members list box and set its DisplayStyle property to ImageAndText, in the right pane of the Items Collection Editor dialog box, as shown in Fig.C#-2.25:

16

17
Fig.C#-2.25 17. Set the Text property of the ToolStripDropDownButton1 node to Alignment (Fig.C#-2.25). 18. Select the DropDownItems property and click the ellipsis button () in front of this property, to add items to the ToolStripDropDownButton1 node, as shown in Fig.C#-2.26:

18

Fig.C#-2.26 The Items Collection Editor dialog box opens for the ToolStripDropDownButton1 item (Fig.C#-2.27). 19. Select the MenuItem option from the Select item and add to list below: drop-down list, as shown in Fig.C#-2.27:

Windows Forms Controls - II 79


19 20

Fig.C#-2.27 20. Click the Add button to add the selected option (Fig.C#-2.27). A control corresponding to the MenuItem option, ToolStripMenuItem1, is added under the ToolStripDropDownMenu node in the Members list box (Fig.C#-2.28). 21. Select the ToolStripMenuItem1 node from the Members list box and set its Text property to Left, in the right pane of the Items Collection Editor dialog box for the ToolStripDropDownButton1 item, as shown in Fig.C#-2.28:

21

Fig.C#-2.28 22. Repeat Step 19 and 20 to add another ToolStripMenuItem control, ToolStripMenuItem2, under the ToolStripDropDownMenu node in the Members list box (Fig.C#-2.29). 23. Select the ToolStripMenuItem2 node from the Members list box and set its Text property to Right, in the right pane of the Items Collection Editor dialog box for the ToolStripDropDownButton1 item (Fig.C#-2.29). 24. Click the OK button to close the Items Collection Editor dialog box for the ToolStripDropDownButton1 item, as shown in Fig.C#-2.29:

23

24
Fig.C#-2.29 25. Click the OK button to close the Items Collection Editor dialog box, as shown in Fig.C#-2.30:

80 Comdex .NET 4.0 Programming Course Kit

25
Fig.C#-2.30 Fig.C#-2.31 shows the StatusStrip1 control in the form after adding items to it:

Fig.C#-2.31 26. Double-click the TextBox control in the form and add the highlighted lines of code, as shown in Listing 2.3, to the Code Editor: Listing 2.3: Showing the Code for the TextBox1_TextChanged Event Handler
private void textBox1_TextChanged(object sender, EventArgs e) { string[] str = textBox1.Text.Split(' '); toolStripStatusLabel1.Text = ("Words: " + str.Length + ", " + "Characters (with spaces): " + textBox1.TextLength); }

Listing 2.3 shows the code for the event handler of the TextChanged event of the TextBox control. This event handler executes when text is entered or changed in the text box at runtime. In the highlighted lines, we have declared an array of String type, named str, which stores words that are delimited by a whitespace or new line from the text entered in the text box. The number of words (number of elements in the str array) and number of characters entered in the text box are displayed in the ToolStripStatusLabel control. 27. Double-click the StatusStrip control in the form and add the highlighted line of code, as shown in Listing 2.4, to the Code Editor: Listing 2.4: Showing the Code to Handle the ItemClicked Event of the StatusStrip Control
private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { MessageBox.Show("Item clicked: " + e.ClickedItem.Name); }

Windows Forms Controls - II 81


Listing 2.4 shows the event handler for the ItemClicked event of the StatusStrip control. This event handler executes when an item of the StatusStrip control is clicked at runtime. The name of the item that was clicked is displayed in a message box. 28. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.32). 29. Enter some text in the text box, Enter text. The ToolStripStatusLabel control of the StatusStrip control displays the number of words and characters entered in the text box, as shown in Fig.C#-2.32:

29

30

Fig.C#-2.32 30. Click the ToolStripDropDownButton control, Alignment (Fig.C#-2.32). A drop-down menu displaying two menu items appears along with a message box displaying the StatusStrip item that you have clicked (Fig.C#-2.33). 31. Click the OK button to close the message box, as shown in Fig.C#-2.33:

31
Fig.C#-2.33 You have learned about the StatusStrip control. In the next section, you learn how to work with dialog boxes in Visual C# 2010.

Working with Dialog Boxes


Visual C# 2010 provides you several built-in dialog boxes to be used in Windows Forms applications. These built-in dialog boxes provide a UI that facilitates interaction between an application and its users to help users to perform a number of tasks, such as changing the font of text entered in a text box, opening a file, saving the changes made in a file, and printing a file. The UI of these built-in dialog boxes consists of controls that contain functionality required to perform a specific task. The dialog boxes available for the Windows Forms applications are represented through some classes, for example, the Font dialog box is represented through the FontDialog class. All the classes that represent these dialog boxes inherit the System.Windows.Forms.CommonDialog class. This class contains the ShowDialog method that displays a dialog box and returns the result of the dialog box. The result returned is a member of the System.Windows.Forms.DialogResult enumeration and it corresponds to the button that is clicked by the user in the dialog box. The members of the DialogResult enumeration are listed in Table 2.12:

82 Comdex .NET 4.0 Programming Course Kit


Table 2.12: Members of the DialogResult Enumeration Member
OK Cancel Yes No Abort Retry Ignore None

Description
Corresponds to the OK button on the dialog box Corresponds to the Cancel button on the dialog box Corresponds to the Yes button on the dialog box Corresponds to the No button on the dialog box Corresponds to the Abort button on the dialog box Corresponds to the Retry button on the dialog box Corresponds to the Ignore button on the dialog box Returns nothing and implies that the dialog box remains visible unless closed explicitly

Visual C# 2010 provides you controls that contain functionality for the built-in dialog boxes available for Windows Forms applications. You can add these controls in a Windows Forms application to allow the users of the application to work with the built-in dialog boxes. These controls are available in the Dialogs and Printing tabs of the Toolbox. Some commonly used dialog box controls are given as follows: The FolderBrowserDialog control The OpenFileDialog control The SaveFileDialog control The FontDialog control The ColorDialog control The PrintDialog and PrintDocument controls Lets now discuss each of these controls, one by one.

Using the FolderBrowserDialog Control


The FolderBrowserDialog control allows users to work with the Browse For Folder dialog box where they can browse through folders, create new folders, and select folders to view the containing files. It displays the available physical drives (such as C: and D:) and the folders on those drives in a hierarchical tree structure. The FolderBrowserDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the FolderBrowserDialog control. Table 2.13 lists the noteworthy properties of the FolderBrowserDialog class: Table 2.13: Noteworthy Properties of the FolderBrowserDialog Class Property
Description RootFolder SelectedPath ShowNewFolderButton

Description
Returns or sets the descriptive text displayed just above the hierarchical tree in the Browse For Folder dialog box. Returns or sets the root folder from where the browsing starts. By default, the desktop is selected as the root location for browsing. Returns or sets the path of the folder selected by a user. Returns or sets a value that indicates whether the Browse For Folder dialog box allows users to create new folders.

Perform the following steps to use the FolderBrowserDialog control in a Windows Forms application: 1. 2. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens.

Windows Forms Controls - II 83


3. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyFolderBrowserDialog (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyFolderBrowserDialog application is created (Fig.C#-2.34). Drag and drop a Label control, a TextBox control, and a Button control on the form from the Toolbox and set the Text properties of the Label control and the Button control to Select a folder: and Browse, respectively, by using the Properties window. Drag and drop a FolderBrowserDialog control on the form from the Dialogs tab of the Toolbox. The FolderBrowserDialog control is also added to the component tray, as shown in Fig.C#-2.34:

4. 5. 6. 7.

8.

Fig.C#-2.34 9. Double-click the Browse button in the form and add the highlighted lines of code, as shown in Listing 2.5, to the Code Editor: Listing 2.5: Showing the Code for the Button1_Click Event Handler
private void button1_Click(object sender, EventArgs e) { folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; DialogResult result=folderBrowserDialog1.ShowDialog(); if (result==DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } }

Listing 2.5 shows the code for the event handler of the Click event of the Button control. This event handler executes when the Browse button on the form is clicked at runtime. In the highlighted lines, we have set the RootFolder property of the FolderBrowserDialog control to Environment.SpecialFolder.MyComputer, which represents the Computer folder of your computer in the current operating system. This implies that when the Browse For Folder dialog box appears, the Computer folder displays as the topmost folder from where you can browse or select a folder. In the If statement, we have called the ShowDialog method of the FolderBrowserDialog control to display the Browse For Folder dialog box and checked whether this method returns OK. When you select a folder and click the OK button in the dialog box, path of the selected folder appears in the text box.

84 Comdex .NET 4.0 Programming Course Kit


10. Press the F5 key on the keyboard to run the application. The output of the application appears, as shown in Fig.C#-2.35:

11

Fig.C#-2.35 11. Click the Browse button on the form to open the Browse For Folder dialog box (Fig.C#-2.35). The Browse For Folder dialog box opens (Fig.C#-2.36). 12. Expand a node representing a drive, under the Computer folder. In our case, we have expanded Local Disk (D:), as shown in Fig.C#-2.36:

12

Fig.C#-2.36 13. Browse and select the desired folder. In our case, we have selected Comdex .NET 4.0 Programming, as shown in Fig.C#-2.37:

13

14
Fig.C#-2.37 14. Click the OK button to select a folder (Fig.C#-2.37). The complete path of the selected folder is added to the text box present on the form, as shown in Fig.C#-2.38:

Windows Forms Controls - II 85

Fig.C#-2.38 In this way, you can use the FolderBrowserDialog control to enable users to browse and select folders in a Windows Forms application.

Using the OpenFileDialog Control


The OpenFileDialog control displays the Open dialog box, which prompts you to select an existing file to view it. With the Open dialog box, you can specify the path of an existing file that you want to open. The OpenFileDialog control first checks whether the specified file exists on the computer; if it exists, the control allows you to open it. The OpenFileDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the OpenFileDialog control. The OpenFileDialog class inherits the FileDialog class. Table 2.14 lists the noteworthy properties of the OpenFileDialog class: Table 2.14: Noteworthy Properties of the OpenFileDialog Class Property
CheckFileExists ShowReadOnly ReadOnlyChecked Multiselect SafeFileName SafeFileNames

Description
Returns or sets a value that indicates whether a warning appears if the user specifies the name of a non-existent file in the Open dialog box Returns or sets a value that indicates whether a read-only check box appears in the dialog box Returns or sets a value that indicates whether the read-only check box appears selected in the dialog box Returns or sets a value that indicates whether multiple files can be selected in the dialog box Returns the file name (not the path) and extension of the file that a user selects in the dialog box Returns an array of the file names (not the path) and extensions of all the files that a user selects in the dialog box

Table 2.15 lists the noteworthy methods of the OpenFileDialog class: Table 2.15: Noteworthy Methods of the OpenFileDialog Class Method
OpenFile Reset

Description
Opens the file selected by a user with read-only permissions Resets all the options in the dialog box to their default values

Perform the following steps to use the OpenFileDialog control in a Windows Forms application: 1. 2. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens.

86 Comdex .NET 4.0 Programming Course Kit


3. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyOpenFileDialog (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyOpenFileDialog application is created (Fig.C#-2.39). Drag and drop a Label control, a PictureBox control, and a Button control on the form from the Toolbox and set the Text properties of the Label control and the Button control to Image file: and Open Image, respectively. Drag and drop an OpenFileDialog control on the form from the Dialogs tab of the Toolbox. The OpenFileDialog control is also added to the component tray, as shown in Fig.C#-2.39:

4. 5. 6. 7.

8.

Fig.C#-2.39 9. Double-click the Open Image button in the form and add the highlighted lines of code, as shown in Listing 2.6, to the Code Editor: Listing 2.6: Showing the Code for the Button1_Click Event Handler
private void button1_Click(object sender, EventArgs e) { DialogResult result=openFileDialog1.ShowDialog(); if ( result != DialogResult.Cancel) { pictureBox1.Image = Image.FromFile(openFileDialog1.FileName); } label1.Text += " " + openFileDialog1.SafeFileName; }

Listing 2.6 shows the code for the event handler of the Click event of the Button control. When the Open Image button is clicked at runtime, the Open dialog box appears which prompts you to select a file. In the If statement, we have called the ShowDialog method of the OpenDialog control to display the Open dialog box and checked whether this method returns a value other than Cancel. The file that you select in the Open dialog box is displayed in the picture box if you click any button other than the Cancel button in the Open dialog box. In addition, the name of the file you select appears in the label. 10. Press the F5 key on the keyboard to run the application. The output of the application appears, as shown in Fig.C#-2.40:

Windows Forms Controls - II 87

11
Fig.C#-2.40 11. Click the Open Image button on the form to display the Open dialog box (Fig.C#-2.40). The Open dialog box appears (Fig.C#-2.41). 12. Browse and select an image file. In our case, we have selected Image1 (Fig.C#-2.41). 13. Click the Open button to set the image in the PictureBox control, as shown in Fig.C#-2.41:

12

13
Fig.C#-2.41 The selected image is displayed in the picture box present on the form and the name of the image file is displayed in the label, as shown in Fig.C#-2.42:

Fig.C#-2.42 In this way, you can use the OpenFileDialog control to enable users to open and work with the files in a Windows Forms application.

Using the SaveFileDialog Control


The SaveFileDialog control allows you to work with the Save As dialog box, which allows users to specify the name, type, and location to save a file. With the SaveFileDialog control, users can either create a new file or overwrite an existing file. The SaveFileDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the SaveFileDialog control. Table 2.16 lists the noteworthy properties of the SaveFileDialog class:

88 Comdex .NET 4.0 Programming Course Kit


Table 2.16: Noteworthy Properties of the SaveFileDialog Class Property
CreatePrompt OverwritePrompt

Description
Returns or sets a value that indicates whether the dialog box prompts the user to create a new file if the user specifies the name of a non-existent file Returns or sets a value to determine whether a warning should appear if the user specifies the name of an existing file

Table 2.17 lists the noteworthy methods of the SaveFileDialog class: L Table 2.17: Noteworthy Methods of the SaveFileDialog Class e Description t Method OpenFile Opens the selected file with the read/write permission s
Reset

Resets all the dialog box options to their default values

Perform the following steps to use the SaveFileDialog control in a Windows Forms application: 1. 2. 3. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. 4. Select the Windows Forms Application template in the right pane to create a Windows Forms application. 5. Enter the name of the application as MySaveFileDialog (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. 6. Click the OK button to close the New Project dialog box. The MySaveFileDialog application is created (Fig.C#-2.43). 7. Drag and drop a Label control, a TextBox control, and a Button control on the form from the Toolbox. 8. Set the Text properties of the Label control and the Button control to Enter text: and Save Text, respectively, by using the Properties window. 9. Set the Multiline property of the TextBox control to True by using the Properties window and then resize the TextBox control to accommodate multiple lines of text. 10. Drag and drop a SaveFileDialog control on the form from the Dialogs tab of the Toolbox. The SaveFileDialog control is also added to the component tray, as shown in Fig.C#-2.43:

Fig.C#-2.43

Windows Forms Controls - II 89


11. Double-click the Save Text button in the form and add the highlighted lines of code, as shown in Listing 2.7, to the Code Editor: Listing 2.7: Showing the Code for the Button1_Click Event Handler
private void button1_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "Text Files (*.txt*)|*.txt*"; saveFileDialog1.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString(); DialogResult result = saveFileDialog1.ShowDialog(); if (result == DialogResult.OK) { if (saveFileDialog1.CheckFileExists == false) { System.IO.File.WriteAllText(saveFileDialog1.FileName, textBox1.Text, System.Text.Encoding.UTF8); } } textBox1.Text = ""; }

Listing 2.7 shows the code for the event handler of the Click event of the Button control. In the highlighted lines, the Filter property of the SaveFileDialog control is set in such a manner that only text files are displayed in the Save As dialog box. In addition, the InitialDirectory property of the SaveFileDialog control is set to the MyDocuments folder on the computer, which implies that the MyDocuments folder is the location that appears by default in the dialog box. When you click the OK button in the Save As dialog box, the If statement checks whether the specified file already exists on the computer. If such a file does not exist, then the text that you entered in the text box is saved in the specified file by using the System.IO.File.WriteAllText method. The Filter and InitialDirectory properties are defined in the FileDialog class, which is inherited by the SaveFileDialog class. 12. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.44). 13. Enter some text in the text box, Enter text, as shown in Fig.C#-2.44:

13

14
Fig.C#-2.44 14. Click the Save Text button to open the Save as dialog box (Fig.C#-2.44). The Save As dialog box appears (Fig.C#-2.45). 15. Select an appropriate location for the file where you want to save the text and enter a name for the file in the File name combo box (Fig.C#-2.45). In our case, we have specified NewTextFile.txt as the name of the file. 16. Click the Save button to save the NewTextFile.txt file, as shown in Fig.C#-2.45:

90 Comdex .NET 4.0 Programming Course Kit

15 16
Fig.C#-2.45 The Save As dialog box closes and the text box on the form becomes empty. Now, if you navigate to the location where you saved the file, you will find the NewTextFile.txt file. You can open the NewTextFile.txt file to see its contents, as shown in Fig.C#-2.46:

Fig.C#-2.46 After learning about the SaveFileDialog control, lets learn about the FontDialog control.

Using the FontDialog Control


The FontDialog control allows you to provide users the facility to work with the Font dialog box. In the Font dialog box, a user can select a font, font size, and font color. Users can also use the Font dialog box to add textual effects, such as underlining the text and applying shadows to the text. The FontDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the FontDialog control. Table 2.18 lists the noteworthy properties of the FontDialog class: Table 2.18: Noteworthy Properties of the FontDialog Class Property
AllowVerticalFonts Color FixedPitchOnly

Description
Returns or sets a value that indicates whether only the horizontal fonts or both vertical and horizontal fonts appear in the dialog box. Returns or sets a Color object that represents the font color selected in the dialog box. Returns or sets a value that indicates whether only fixed-pitch fonts can be selected in the dialog box. Fixed-pitch fonts are those fonts in which all the characters have the same width. Returns or sets a Font object that represents the font selected in the dialog box. Returns or sets a value that indicates whether an error message is displayed to the users if a user specifies a non-existent font or font style. Returns or sets the maximum font size that a user can specify. Returns or sets the minimum font size that a user can specify. The default value for this property is zero. Returns or sets a value that indicates whether an Apply button appears in the dialog box or not.

Font FontMustExist MaxSize MinSize ShowApply

Windows Forms Controls - II 91


ShowColor ShowEffects ShowHelp Returns or sets a value that indicates whether the dialog box provides the facility to select a font color or not. Returns or sets a value that indicates whether the dialog box provides the facility to select textual effects, such as strikeout and underline. Returns or sets a value that indicates whether a Help button appears in the dialog box or not.

Table 2.19 lists a noteworthy event of the FontDialog class: Table 2.19: Noteworthy Event of the FontDialog Class Event
Apply

Description
Occurs when a user clicks the Apply button in the Font dialog box

Perform the following steps to use the FontDialog control in a Windows Forms application: 1. 2. 3. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyFontDialog (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyFontDialog application is created (Fig.C#-2.47). Drag and drop a Label control, a TextBox control, and a Button control on the form from the Toolbox and set the Text properties of the Label control and the Button control to Enter text: and Change Font, respectively, by using the Properties window. Drag and drop a FontDialog control on the form from the Dialogs tab of the Toolbox. The FontDialog control is also added to the component tray, as shown in Fig.C#-2.47:

4. 5. 6. 7.

8.

Fig.C#-2.47 9. Double-click the Change Font button in the form and add the highlighted lines of code, as shown in Listing 2.8, to the Code Editor:

92 Comdex .NET 4.0 Programming Course Kit


Listing 2.8: Showing the Code for the Button1_Click Event Handler
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click fontDialog1.FontMustExist = true; fontDialog1.ShowColor = true; fontDialog1.ShowHelp = true; DialogResult result = fontDialog1.ShowDialog(); if (result == DialogResult.OK) { textBox1.Font = fontDialog1.Font; textBox1.ForeColor = fontDialog1.Color; } }

Listing 2.8 shows the code for the event handler of the Click event of the Button control. In the highlighted lines, we have first set the FontMustExist, ShowColor, and ShowHelp properties of the FontDialog control to True. This implies that the Font dialog box will display options to select font and font color, along with a Help button. In addition, if you specify a font that does not exist, an error message appears. When you click the OK button in the Font dialog box, then the font and the color selected in the Font dialog box are applied to the text in the text box on the form. 10. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.48). 11. Enter some text in the text box, Enter text. In our case, we have entered Welcome to Visual C# 2010!, as shown in Fig.C#-2.48:

11

12

Fig.C#-2.48 12. Click the Change Font button on the form to change the font of the text entered in the text box, Enter text (Fig.C#-2.48). The Font dialog box appears (Fig.C#-2.49). 13. Select a font from the Font combo box. In our case, we have selected Monotype Corsiva (Fig.C#-2.49). 14. Select a font style from the Font style combo box. In our case, we have selected Italic (Fig.C#-2.49). 15. Select a font size from the Size combo box. In our case, we have selected 12 (Fig.C#-2.49). 16. Click the down arrow button of the Color drop-down list to select a font color, as shown in Fig.C#-2.49:

Windows Forms Controls - II 93

14 13 15

16
Fig.C#-2.49 17. Select a font color from the drop-down menu that appears. In our case, we have selected Red, as shown in Fig.C#-2.50:

18

17

Fig.C#-2.50 18. Click the OK button to close the Font dialog box (Fig.C#-2.50). The selected font and font color are applied to the text in the text box present on the form, as shown in Fig.C#-2.51:

Fig.C#-2.51 You have learned to use the FontDialog control to change the font, size, and color of text with the Font dialog box. However, the range of colors provided in the Font dialog box is very limited. Therefore, Visual C# 2010 provides you the Color dialog box, which can be used along with the Font dialog box to work with more colors and shades. The Color dialog box is available for Windows Forms applications through the ColorDialog control. The next section discusses the ColorDialog control.

94 Comdex .NET 4.0 Programming Course Kit


Using the ColorDialog Control
The ColorDialog control allows you to use the Color dialog box, which provides you with a variety of predefined colors to select. You can also make new colors by mixing different colors and selecting different values for hue, saturation, and luminosity of the new color. The ColorDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the ColorDialog control. Table 2.20 lists the noteworthy properties of the ColorDialog class: Table 2.20: Noteworthy Properties of the ColorDialog Class Property
AllowFullOpen AnyColor Color CustomColors FullOpen ShowHelp SolidColorOnly

Description
Returns or sets a value that indicates whether the dialog box provides users with the facility to define custom colors. Returns or sets a value that indicates whether the dialog box displays all the available colors in the set of basic colors. Returns or sets a Color object that represents the color selected by a user. The default color is Black. Returns or sets the set of custom colors shown in the dialog box. By default, this property holds a null value. Returns or sets a value that indicates whether the options that allow users to define custom colors are visible when the dialog box is first opened. Returns or sets a value that indicates whether a Help button appears in the dialog box. Returns or sets a value that indicates whether the users can select only the solid colors in the dialog box.

Perform the following steps to use the ColorDialog control in a Windows Forms application: 1. 2. 3. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as MyColorDialog (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The MyColorDialog application is created (Fig.C#-2.52). Drag and drop a Label control and a Button control on the form from the Toolbox and set the Text properties of the Label control and the Button control to Welcome to Visual C# 2010 and Change Background Color, respectively, by using the Properties window. Drag and drop a ColorDialog control on the form from the Dialogs tab of the Toolbox. The ColorDialog control is also added to the component tray, as shown in Fig.C#-2.52:

4. 5. 6. 7.

8.

Windows Forms Controls - II 95

Fig.C#-2.52 9. Double-click the Change Background Color button in the form and add the highlighted lines of code, as shown in Listing 2.9, to the Code Editor: Listing 2.9: Showing the Code for the Button1_Click Event Handler
private void button1_Click(object sender, EventArgs e) { colorDialog1.ShowHelp = true; DialogResult result = colorDialog1.ShowDialog(); if (result == DialogResult.OK) { label1.BackColor = colorDialog1.Color; } }

Listing 2.9 shows the code for the event handler of the Click event of the Button control. In the highlighted lines, we have first set the ShowHelp property of the FontDialog control to True. This implies that the Color dialog box will display a Help button. The Color dialog box appears when you click the Change Background Color button. After you select a color in the Color dialog box and click the OK button, the selected color is set as the background color of the label on the form. 10. Press the F5 key on the keyboard to run the application. The output of the application appears, as shown in Fig.C#-2.53:

11

Fig.C#-2.53 11. Click the Change Background Color button on the form to change the background color of the label present on the form (Fig.C#-2.53). The Color dialog box appears (Fig.C#-2.54). 12. Select a color under the Basic colors option (Fig.C#-2.54).

96 Comdex .NET 4.0 Programming Course Kit


13. Click the OK button to close the Color dialog box, as shown in Fig.C#-2.54:

12

13
Fig.C#-2.54 The background color of the label present on the form changes to the color selected in the Color dialog box, as shown in Fig.C#-2.55:

14

Fig.C#-2.55 14. Click the Change Background Color button on the form again to use a custom color to set the background color of the label present on the form (Fig.C#-2.55). The Color dialog box appears (Fig.C#-2.56). 15. Click the Define Custom Colors button, as shown in Fig.C#-2.56:

15
Fig.C#-2.56 The Color dialog box is expanded to allow you to define a custom color, as shown in Fig.C#-2.57:

Windows Forms Controls - II 97

16
Fig.C#-2.57 You need to select hue, saturation, and luminosity for the color to define a custom color. 16. Select the appropriate color combination from the large box displayed beside the Basic colors option or enter values for hue and saturation in the Hue and Sat text boxes, respectively, to specify hue and saturation for the new color (Fig.C#-2.57). 17. Select the appropriate shade in the vertical strip on the extreme right of the Color dialog box or enter the value for luminosity in the Lum text box, to specify luminosity for the new color, as shown in Fig.C#-2.58:

17

Fig.C#-2.58 18. Click the Add to Custom Colors button, as shown in Fig.C#-2.59:

18
Fig.C#-2.59 The new color is added to the first box under the Custom colors option, as shown in Fig.C#-2.60:

19 20
Fig.C#-2.60

98 Comdex .NET 4.0 Programming Course Kit


19. Select the custom color that you have just defined (Fig.C#-2.60). 20. Click the OK button to close the Color dialog box (Fig.C#-2.60). The custom color is set as the background color of the label present on the form, as shown in Fig.C#-2.61:

Fig.C#-2.61 After learning about the dialog box controls available under the Dialogs tab of the Toolbox, lets now discuss the dialog box controls that are used for printing documents, available under the Printing tab of the Toolbox.

Using the PrintDialog and PrintDocument Controls


Visual C# 2010 provides you several controls with printing functionality that you can use to print documents in your Windows Forms applications. Two main printing controls available for Windows Forms applications are given as follows: The PrintDialog control: Displays the Print dialog box that facilitates you to print a document. The Print dialog box allows you to select a printer and specify various options and settings, such as number of pages of the document and copies of each page need to print. The PrintDialog class, which is placed inside the System.Windows.Forms namespace, provides the functionality for the PrintDialog control. The PrintDocument control: Represents the document to print. This control allows you to set various options and settings to print a document. Note that the PrintDocument control does not have any UI; therefore, it is not visible at runtime. The PrintDocument class, which is placed inside the System.Drawing.Printing namespace, provides the functionality for the PrintDocument control. Table 2.21 lists the noteworthy properties of the PrintDialog class:

Table 2.21: Noteworthy Properties of the PrintDialog Class Property


AllowCurrentPage AllowPrintToFile AllowSomePages Document PrinterSettings PrintToFile

Description
Returns or sets a value that indicates whether the users have the facility to print only the current page Returns or sets a value that indicates whether the Print to file check box is enabled in the dialog box Returns or sets a value that indicates whether the users have the facility to print a range of pages Returns or sets the PrintDocument object Returns or sets the printer settings that are changed in the dialog box Returns or sets a value that indicates whether the Print to file check box appears selected in the dialog box

Windows Forms Controls - II 99


Table 2.22 lists a noteworthy method of the PrintDialog class: Table 2.22: Noteworthy Method of the PrintDialog Class Method
Reset

Description
Allows you to reset all the options in the Print dialog box to their default values

Table 2.23 lists the noteworthy properties of the PrintDocument class: Table 2.23: Noteworthy Properties of the PrintDocument Class Property
DefaultPageSettings DocumentName PrinterSettings

Description
Returns or sets the default settings for all the pages to be printed Returns or sets the name of the document to display while printing it Returns or sets the settings of the printer that is used to print the document

Table 2.24 lists a noteworthy method of the PrintDocument class: Table 2.24: Noteworthy Method of the PrintDocument Class Method
Print

Description
Allows you to start the process of printing a document

Table 2.25 lists the noteworthy events of the PrintDocument class: Table 2.25: Noteworthy Events of the PrintDocument Class Event
BeginPrint EndPrint PrintPage QueryPageSettings

Description
Occurs after the Print method is called but before the first page is printed Occurs after the last page of the document is printed Occurs when output to print for the current page is needed Occurs just before a PrintPage event occurs

Perform the following steps to use the PrintDialog and PrintDocument controls in a Windows Forms application: 1. 2. 3. Start Visual Studio 2010. Select FileNewProject from the menu bar. The New Project dialog box opens. Select Visual C#Windows from the Installed Templates section in the left pane of the New Project dialog box. The project templates available for developing Windows-based applications in Visual C# are displayed in the right pane of the New Project dialog box. Select the Windows Forms Application template in the right pane to create a Windows Forms application. Enter the name of the application as PrintingControls (also available on the CD) in the Name text box and an appropriate location for the application in the Location box. Click the OK button to close the New Project dialog box. The PrintingControls application is created (Fig.C#-2.62). Drag and drop a Label control, a TextBox control, and a Button control on the form from the Toolbox. Set the Text properties of the Label control and the Button control to Enter text: and Print, respectively, by using the Properties window.

4. 5. 6. 7. 8.

100 Comdex .NET 4.0 Programming Course Kit


Set the Multiline property of the TextBox control to True by using the Properties window and then resize the TextBox control to accommodate multiple lines of text. 10. Drag and drop a PrintDialog control and a PrintDocument control on the form from the Printing tab of the Toolbox. Both these controls are also added to the component tray, as shown in Fig.C#-2.62: 9.

Fig.C#-2.62 11. Double-click the Print button in the form and add the highlighted lines of code, as shown in Listing 2.10, to the Code Editor: Listing 2.10: Showing the Code for the Button1_Click Event Handler
private void button1_Click(object sender, EventArgs e) { printDocument1.DocumentName = "My Custom Document"; printDialog1.Document = printDocument1; printDialog1.AllowSomePages = true; printDialog1.AllowCurrentPage = true; DialogResult result= printDialog1.ShowDialog(); if (result==DialogResult.OK) { printDocument1.PrinterSettings = printDialog1.PrinterSettings; printDocument1.Print(); } }

Listing 2.10 shows the code for the event handler of the Click event of the Button control. In the highlighted lines, we have first set the DocumentName property of the PrintDocument1 control to My Custom Document. This implies that the text, My Custom Document, appears as the name of the document while printing. After that, set the Document property of the PrintDialog control to the PrintDocument control, PrintDocument1. This implies that the document to be printed by using the PrintDialog1 control is PrintDocument1. In addition, the AllowSomePages and AllowCurrentPage properties of the PrintDialog control are set to True meaning that the Print dialog box contains options to print a sequence of pages as well as only the current page. When you click the Print button (equivalent to the OK button in other dialog boxes) in the Print dialog box, the settings specified in the Print dialog box are applied to the PrintDocument control and the Print method of the PrintDocument control is called to start printing. 12. Double-click the PrintDocument control in the component tray and add the highlighted lines of code, as shown in Listing 2.11, to the Code Editor:

Windows Forms Controls - II 101


Listing 2.11: Showing the Code for the PrintDocument1_PrintPage Event Handler
private void printDocument1_PrintPage(object sender, System.Drawing.Printing. PrintPageEventArgs e) { Font textFont = new Font("Arial", 14, FontStyle.Bold); e.Graphics.DrawString(textBox1.Text, textFont, Brushes.Black, new Rectangle(50, 50, e.PageBounds.Height, e.PageBounds.Width)); }

Listing 2.11 shows the code for the event handler of the PrintPage event of the PrintDocument control. In the highlighted lines, we have first created the textFont object of the Font class and then set its font, font size, and font style to Arial, 14, and Bold, respectively. After that, we have called the DrawString method of the e.Graphics object to print the text in the TextBox control. The DrawString method prints the text by using the Font, Brushes, and Rectangle objects of the System.Drawing namespace. 13. Press the F5 key on the keyboard to run the application. The output of the application appears (Fig.C#-2.63). 14. Enter some text in the text box, Enter text, as shown in Fig.C#-2.63:

14

15
Fig.C#-2.63 15. Click the Print button to open the Print dialog box (Fig.C#-2.63). The Print dialog box appears that displays various options to customize the way you want to print the text (Fig.C#-2.64). 16. Select the desired options in the Print dialog box. In our case, we have selected the Current Page radio button in the Page Range group and specify 2 in the Number of copies spin box (Fig.C#-2.64). 17. Click the Print button to start printing, as shown in Fig.C#-2.64:

16 17
Fig.C#-2.64 The text is printed on the default printer specified for your computer.

102 Comdex .NET 4.0 Programming Course Kit

Summary
In this chapter, you have learned how to work with the ToolStrip control, which allows you to include a toolbar in Windows Forms applications. You have also learned about the MenuStrip control and the StatusStrip control that enables you to add menus and submenus and display the information about other controls or instructions to perform a task, respectively. In addition, the chapter discussed the controls such as FolderBrowserDialog, OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDialog, and PrintingDocument that allow you to work with some of the common built-in dialog boxes.

S-ar putea să vă placă și