Documente Academic
Documente Profesional
Documente Cultură
2
Windows Forms Controls - II
In this Chapter:
Using the ToolStrip Control Using the MenuStrip Control Using the StatusStrip Control Working with Dialog Boxes
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
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
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.
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
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); }
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.
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
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!).
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.
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:
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:
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:
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:
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:
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:
27
Fig.C#-2.21 Lets now learn about the StatusStrip control.
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.
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:
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:
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:
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); }
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.
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.
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.
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.
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:
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.
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.
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:
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.
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
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
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:
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.
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.
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:
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:
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.
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.
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).
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:
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
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.
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
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.
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:
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.
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.