5 TLSTRP, Menustrp, CntxtMenustrp, StatusStrp, Dlgboxcntrl
5 TLSTRP, Menustrp, CntxtMenustrp, StatusStrp, Dlgboxcntrl
5 TLSTRP, Menustrp, CntxtMenustrp, StatusStrp, Dlgboxcntrl
Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
If you need an Immediate Solution to:
Using the ToolStrip Control Using the MenuStrip and ContextMenuStrip Controls Using the StatusStrip Control Using the Dialog Box Controls
See page:
162 165 177 180
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
In Depth
You must be familiar with common Windows or Microsoft Office applications, such as Notepad, WordPad, Word, or Excel. All these applications provide a graphical user interface (GUI) with menus, toolbars, context menus, status bars, and dialog boxes to allow the users to perform various activities. Visual C# 2010 provides various controls to create such applications, along with their GUIs. Some examples of these controls are: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, OpenFileDialog, and PrintDialog. The ToolStrip, MenuStrip, and ContextMenuStrip controls enable you to perform common functions and make selections in an application, such as copying and pasting the text, saving a file, or changing the size or alignment of the text. You can also use the StatusStrip control in your application to show its status, for instance to show the number of lines in your document. Visual C# 2010 also provides various dialog box controls to handle the opening, saving, or printing of your files, or to set the font type or color for the text in your application. These controls include FolderBrowserDialog, OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDocument, PageSetupDialog, PrintPreviewControl, PrintPreviewDialog, and PrintDialog. In this chapter, you learn about different Windows Forms controls. The chapter begins with the ToolStrip and MenuStrip controls, and the ToolStripItem and ToolStripMenuItem classes to create toolbars and menus in your applications. Next, you learn to create context menus and status bars using the ContextMenuStrip and StatusStrip controls, respectively. Finally, you learn about different dialog box controls to handle common tasks related to the opening, saving, or printing of files; and selecting the font type or color of the text.
The ToolStrip control is based on the ToolStrip class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ScrollableControl System.Windows.Forms.ToolStrip
The noteworthy properties of the ToolStrip class are listed in Table 5.1:
136
Description
Retrieves or sets a value indicating whether or not drag-and-drop and item reordering are handled through events that you implement. The value of this property can be either true or false. Retrieves or sets a value indicating whether or not the ToolStrip class handles drag-and-drop and item reordering privately. Retrieves or sets a value indicating whether or not multiple MenuStrip, ToolStripDropDownMenu, ToolStripMenuItem, and other types can be combined on a ToolStrip control. Retrieves or sets the edges of the container to which a ToolStrip control is bound, and determines how a ToolStrip control is resized with its parent. Specifies whether a value indicating the control is automatically resized or not. Retrieves or sets the binding context for the ToolStrip control. Retrieves or sets a value indicating whether or not items in the ToolStrip control can be shown in an overflow menu. Retrieves or sets a value indicating whether or not validation is performed when an item within the ToolStrip control is selected. Retrieves or sets a value representing the direction in which a ToolStripDropDown control is displayed relative to the ToolStrip control. Retrieves or sets the ToolStrip control borders that are docked to the parent control, and determines how a ToolStrip control is resized. Retrieves or sets the font used to display text in the control. Retrieves or sets the foreground color of the ToolStrip control. Retrieves the orientation of the ToolStrip control move handle. Retrieves or sets the space around the ToolStrip control move handle. Retrieves the boundaries of the ToolStrip control move handle. Retrieves or sets whether or not the ToolStrip control move handle is visible or hidden. Retrieves or sets the image list that contains the image displayed on a ToolStrip item. Retrieves or sets the size, in pixels, of an image used on a ToolStrip control. Retrieves a value indicating the current movement of the ToolStrip control by the user from one ToolStripContainer to another. Retrieves a value indicating ToolStripDropDown control. whether or not a ToolStrip is a
AllowItemReorder AllowMerge
Anchor AutoSize BindingContext CanOverflow CausesValidation DefaultDropDownDirection Dock Font ForeColor GripDisplayStyle GripMargin GripRectangle GripStyle ImageList ImageScalingSize IsCurrentlyDragging IsDropDown Items LayoutEngine LayoutSettings LayoutStyle Orientation
Retrieves all the items belonging to a ToolStrip control. Passes a reference to the cached LayoutEngine returned by the layout engine interface. Retrieves or sets layout scheme characteristics. Retrieves or sets a value indicating how the ToolStrip control places the collection of items on the screen. Specifies the orientation of the ToolStripPanel control.
137
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.1: Noteworthy Properties of the ToolStrip Class Property
OverflowButton Renderer RenderMode ShowItemToolTips Stretch TabStop TextDirection
Description
Retrieves the ToolStripItem element that is the overflow button for a ToolStrip control, with overflow enabled. Retrieves or sets a ToolStripRenderer used to customize the look and feel of a ToolStrip control. Retrieves or sets the painting styles to be applied to the ToolStrip control. Retrieves or sets a value indicating whether or not ToolTips are displayed on ToolStrip items. Retrieves or sets a value indicating whether or not the ToolStrip control stretches from end to end in the ToolStripContainer control. Retrieves or sets a value indicating whether or not the user can give the focus to an item in the ToolStrip control using the TAB key. Retrieves or sets the direction in which to draw text on a ToolStrip control.
The only noteworthy method of the ToolStrip class is the GetNextItem() method, which is used to retrieve the next ToolStripItem from a specified reference point. Table 5.2 lists the noteworthy events of the ToolStrip class:
Table 5.2: Noteworthy Events of the ToolStrip Class Event
AutoSizeChanged BeginDrag CausesValidationChanged CursorChanged EndDrag ForeColorChanged ItemAdded ItemClicked ItemRemoved LayoutCompleted LayoutStyleChanged PaintGrip RendererChanged
Description
Occurs when the AutoSize property is changed Occurs when the user begins to drag the ToolStrip control Occurs when the CausesValidation property changes Occurs when the Cursor property changes Occurs when the user stops dragging the ToolStrip control Occurs when the value of the ForeColor property changes Occurs when a new ToolStripItem is added to the ToolStripItemCollection control Occurs when the ToolStripItem control is clicked Occurs if when a ToolStripItem is removed from the ToolStripItemCollection control Occurs when the layout of the ToolStrip control is complete Occurs when the value of the LayoutStyle property changes Occurs when the ToolStrip control move handle is painted Occurs when the value of the Renderer property changes
Typically, the items in a ToolStrip control correspond to the most popular menu items in the application. If you click a tool strip item, it activates the corresponding menu item. In such cases, the code for ToolStrip items is easy to implement. You need to call the PerformClick() method of the corresponding ToolStripMenuItem object of the menu strip, which in turn activates the menu item. The Items property of the ToolStrip control allows a user to add tool strip items to the tool strip. When the user points the mouse pointer at a ToolStrip button, tool tip is displayed.
138
In Depth
The ShowItemToolTips property, when set to true, can display tool tips on a ToolStrip control.
You can add various types of controls to a ToolStrip control. Some examples of these controls are buttons, push buttons, toggle buttons, drop-down buttons, and split buttons. The TextAlign property specifies the alignment of the text in a button, such as the top or bottom alignment of the button. You can also add images to the tool strip items. The DisplayStyle property can be used to specify whether you want a text, an image, or both on the tool strip item. The TextImageRelation property specifies the relative placement of the image with respect to the text on a ToolStripItem. The next section deals with the ToolStripItem class, which is used for adding items to the toolbar.
The noteworthy properties of the ToolStripItem class are given in Table 5.3:
Table 5.3: Noteworthy Properties of the ToolStripItem Class Property
Alignment AllowDrop Anchor AutoSize AutoToolTip Available BackColor BackgroundImageLayout Bounds CanSelect ContentRectangle
Description
Retrieves or sets a value that signifies whether the item aligns towards the start or the end of the ToolStrip control Retrieves or sets a value signifying whether drag-and-drop and item reordering is handled through events that you implement Retrieves or sets the edges of the container to which a ToolStripItem is bound, and determines how a ToolStripItem is resized with its parent Retrieves or sets a value signifying whether or not the item is automatically resized Retrieves or sets a value indicating whether to use the Text property or the ToolTipText property for the ToolStripItem ToolTip Retrieves or sets a value indicating whether or not the ToolStripItem control should be placed on a ToolStrip control Retrieves or sets the background color for the item Retrieves or sets the background image layout used for the ToolStripItem control Retrieves the size and location of the item Retrieves a value indicating whether or not the item can be selected Retrieves the area where content, such as text and icons, can be placed within a ToolStripItem without overwriting background borders
139
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.3: Noteworthy Properties of the ToolStripItem Class Property
DisplayStyle Dock DoubleClickEnabled Enabled Font ForeColor Height Image ImageAlign ImageIndex ImageScaling ImageTransparentColor IsDisposed IsOnDropDown IsOnOverflow Margin MergeAction MergeIndex Name Overflow Owner OwnerItem Padding Placement Pressed RightToLeft RightToLeftAutoMirrorImage Selected
Description
Retrieves or sets whether or not the text and images are displayed on a ToolStripItem Retrieves or sets which ToolStripItem borders are docked to its parent control and determines how a ToolStripItem is resized with its parent Retrieves or sets a value indicating whether or not the ToolStripItem control can be activated by double clicking the mouse Retrieves or sets a value indicating whether or not the parent control of the ToolStripItem control is enabled Retrieves or sets the font of the text displayed by the item Retrieves or sets the foreground color of the item Retrieves or sets the height, in pixels, of the ToolStripItem control Retrieves or sets the image displayed on the ToolStripItem control Retrieves or sets the alignment of the image on the ToolStripItem control Retrieves or sets the index value of the image that is displayed on the item Retrieves or sets a value indicating whether or not an image on the ToolStripItem control is automatically resized to fit in a container Retrieves or sets the color to treat as transparent in a ToolStripItem image Retrieves a value indicating whether or not the object or control has been disposed off Retrieves a value indicating whether or not the container of the current control is a ToolStripDropDown control Retrieves a value indicating whether or not the Placement property is set to Overflow Retrieves or sets the space between the item and adjacent items Specifies how child menus are merged with parent menus Retrieves or sets the position of a merged item within the current ToolStrip Retrieves or sets the name of the item Retrieves or sets whether or not the item is attached to the ToolStrip or ToolStripOverflowButton control or can float between the two Retrieves or sets the owner of the ToolStripItem control Retrieves the parent ToolStripItem class of the ToolStripItem control Retrieves or sets the internal spacing, in pixels, between an items contents and its edges Retrieves the current layout of the item Retrieves a value indicating whether or not the ToolStripItem control is pressed Retrieves or sets a value specifying whether or not items should be placed from right to left and the text should be written from right to left Automatically mirrors the ToolStripItem image when the RightToLeft property is set to Yes Retrieves a value indicating whether or not the item is selected or not
140
Description
Retrieves or sets the size of the item Retrieves or sets the object that contains data about the item Retrieves or sets the text that is to be displayed on the item Retrieves or sets the alignment of the text on a ToolStripLabel Retrieves the orientation of text used on a ToolStripItem Retrieves or sets the position of the ToolStripItem text and image relative to each other Retrieves or sets the text that appears as a ToolTip for a control Retrieves or sets a value specifying whether or not the item is displayed or not Retrieves or sets the width, in pixels, of a ToolStripItem control
Description
Starts a drag-and-drop operation Retrieves a ToolStrip object that contains the current ToolStripItem control Retrieves a rectangular area into which a control fits Invalidates a part or the entire surface of the control and causes the control to be redrawn Activates the ToolStripItem control when its Click event occurs Selects the specified item
Description
Occurs when the value of the Available property changes Occurs when the value of the BackColor property changes Occurs when the ToolStripItem control is clicked Occurs when the DisplayStyle property changes Occurs when the item is double-clicked Occurs when the user drags an item and then releases the mouse button, indicating that the item should be dropped into this item Occurs when the user drags an item into the client area of the ToolStripItem control Occurs when the user drags an item and the mouse pointer is no longer over the client area of this item Occurs when the user drags an item over the client area of this item Occurs when the value of the Enabled property changes
141
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.5: Noteworthy Events of the ToolStripItem Class Event
ForeColorChanged GiveFeedback LocationChanged MouseDown MouseEnter MouseHover MouseLeave MouseMove MouseUp OwnerChanged Paint QueryAccessibilityHelp RightToLeftChanged TextChanged VisibleChanged
Description
Occurs when the value of the ForeColor property changes Occurs at a drag operation Occurs when the location of the ToolStripItem control is changed Occurs when the mouse pointer is placed over the item and a mouse button is pressed Occurs when the mouse pointer enters the item Occurs when the mouse pointer hovers over the item Occurs when the mouse pointer leaves the item Occurs when the mouse pointer is moved over the item Occurs when the mouse pointer is over the item and a mouse button is released Occurs when the Owner property value changes Occurs when the item is redrawn Occurs when an accessibility client application invokes help for the ToolStripItem control Occurs when the value of the RightToLeft property changes Occurs when the Text property value changes Occurs when the Visible property value changes
142
In Depth
There are two main classes in the standard menu handling: MenuStripActs as a container for the menu structure of a form ToolStripMenuItem Supports the items in a menu system (including the menus, such as File and Edit) The class hierarchy of the MenuStrip class is as follows:
The noteworthy properties of the MenuStrip class are given in Table 5.6:
Table 5.6: Noteworthy Properties of the MenuStrip Class Property
CanOverflow GripStyle MdiWindowListItem ShowItemToolTips Stretch
Description
Retrieves or sets a value indicating whether or not the MenuStrip control supports overflow functionality Retrieves or sets the visibility of the grip used to reposition the control Retrieves or sets the ToolStripMenuItem control used to display a list of Multiple-Document Interface (MDI) child forms Retrieves or sets a value indicating whether or not tool tips are shown for the MenuStrip control Retrieves or sets a value indicating whether or not the MenuStrip control stretches from end to end in its container
Description
Occurs when the user accesses the menu with the keyboard or mouse Occurs when the MenuStrip control is deactivated
You can add submenus to the menus that pop up when the user clicks an arrow in a menu item, display check marks, create menu separator bars used to group menu items, assign shortcut keys (such as CTRL + H) to menu items and add images to menu items. You can also draw the appearance of menu items. These actions are supported by ToolStripMenuItem objects, but not by MenuStrip objects.
There are many menu conventions in Windows that you should adhere to if you are creating your programs for public use. Some of the menu conventions in Windows are listed as follows:
z z z z
If a menu item opens a dialog box, you should add an ellipsis (...) after its name (such as Print...). There are many standard shortcuts already in use, such as CTRL+S for Save, CTRL+X for Cut, CTRL+V for Paste, and CTRL+C for Copy. Therefore, do not assign any different shortcuts for these functions. Menus in the menu bar that do not open a menu but instead perform some action immediately should have an exclamation point (!) after their names (such as Connect!). The File menu should always be the first menu, and an Exit item should be the last item of that menu.
Lets now take a look at the ToolStripMenuItem class, which adds menus and its menu items to a standard menu bar.
143
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
The ToolStripMenuItem class supports the menus and menu items in a menu system. These menu items are objects that you can handle through the Click events in a menu system. The class hierarchy of the ToolStripMenuItem class is as follows:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.ToolStripItem System.Windows.Forms.ToolStripDropDownItem System.Windows.Forms.ToolStripMenuItem
The noteworthy properties of the ToolStripMenuItem class are given in Table 5.8:
Table 5.8: Noteworthy Properties of the ToolStripMenuItem Class Property
Checked CheckOnClick CheckState Enabled IsMdiWindowListEntry ShortcutKeyDisplayString ShortcutKeys ShowShortcutKeys
Description
Retrieves or sets a value indicating whether or not the ToolStripMenuItem control is checked Retrieves or sets a value specifying whether or not the ToolStripMenuItem control should automatically appear checked and unchecked when clicked Retrieves or sets a value indicating whether or not a ToolStripMenuItem is in the checked, unchecked, or indeterminate state Retrieves or sets a value indicating whether or not the control is enabled Retrieves a value indicating whether or not the ToolStripMenuItem control appears on an MDI window list Retrieves or sets the shortcut key text Retrieves or sets the shortcut keys associated with the ToolStripMenuItem control Retrieves or sets a value indicating whether or not the shortcut keys that are associated with the ToolStripMenuItem control are displayed next to the ToolStripMenuItem control
Description
Occurs when the value of the Checked property changes Occurs when the value of the CheckState property changes
The ToolStripMenuItem class provides properties that enable you to configure the appearance and functionality of a menu item. To display a checkmark next to a menu item, use the Checked property. This feature also identifies a menu item that is selected in a list of mutually exclusive menu items. The ShortcutKeys property defines a keyboard combination (such as CTRL + X) that can be pressed to select the menu item. The key combination is displayed in the menu items caption by setting the ShowShortcutKeys property to True. ToolStripMenuItem objects can also have other ToolStripMenuItem objects attached to them, to display submenus.
144
In Depth
To set the caption of a menu or menu item, you can use the Text property. Setting the Text property to a hyphen (-) converts the menu item into a menu separator, or the horizontal bars that group menu items together. (You can even have separators in menu bars, in which case they are vertical.) Prefixing a character in a menu items caption with an ampersand (&) underlines that character and makes it into an access key, which means that the user can select that item by pressing the ALT key and underlined character on the keyboard. For example, in a menu item, the caption E&xit makes x as the access key for this menu item. You can enable and disable menu items with the Enabled property, and show or hide them with the Visible property. In the next section, you learn about the context menus.
The ContextMenuStrip control is supported by the ContextMenuStrip class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ScrollableControl System.Windows.Forms.ToolStrip System.Windows.Forms.ToolStripDropDown System.Windows.Forms.ToolStripDropDownMenu System.Windows.Forms.ContextMenuStrip
The only noteworthy property of the ContextMenuStrip class is the SourceControl property, which is used to retrieve the last control that displayed the ContextMenuStrip control. You associate context menus with other controls by setting the controls ContextMenuStrip property to the ContextMenuStrip control. The central property of the ContextMenuStrip control is the ToolStripMenuItems
145
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
property. You can add menu items to a context menu at design time or in code by creating ToolStripMenuItem objects and adding them to the ToolStripMenuItems collection of the context menu. Similar to the main menus, context menu items can be disabled, hidden, or deleted. You can also show the context menus with the help of the Show() method of the ContextMenuStrip control. You can handle the menu items Click, Select, and Popup events, as you can in main menus. In fact, the only major difference is that the context menus are not divided into separate menus, such as File, Edit, and Window.
A context menu can be associated with a number of other controls, but each control can have only one context menu.
Description
Retrieves or sets a value indicating whether or not the StatusStrip control supports overflow functionality Specifies the StatusStrip borders that are docked to its parent control, and determines how a StatusStrip control is resized with its parent control
146
Description
Retrieves or sets the visibility of the grip or the sizing handle used to reposition the control Retrieves or sets a value indicating how items are arranged on the StatusStrip control Retrieves or sets a value indicating whether or not tooltips are shown for the StatusStrip control Retrieves the boundaries of the sizing handle (grip) for a StatusStrip control Retrieves or sets a value indicating whether or not a sizing handle is displayed in the lower-right corner of the control Retrieves or sets a value indicating whether or not the StatusStrip control stretches from end to end in its container
The StatusStrip control provides the following controls, which are used for displaying any type of status information in an application: StatusLabelDisplays messages ProgressBarDisplays the progress of a background task, such as saving the document or sending it to the printer DropDownButtonDisplays a drop-down list SplitButtonRepresents a combination of a standard button on the left and a drop-down button on the right Now, lets take a look at the built-in dialog boxes and their corresponding controls.
AbortReturns an Abort value when the user clicks a button labeled Abort CancelReturns a Cancel value when the user clicks a button labeled Cancel IgnoreReturns an Ignore value when the user clicks a button labeled Ignore NoReturns a No value when the user clicks a button labeled No
147
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
NoneReturns nothing. This means that the modal dialog box continues running OKReturns an OK value when the user clicks a button labeled OK RetryReturns a Retry value when the user clicks a button labeled Retry YesReturns a Yes value when the user clicks a button labeled Yes Lets take a closer look at these dialog boxes now.
The FolderBrowserDialog control is based on the FolderBrowserDialog class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.CommonDialog System.Windows.Forms.FolderBrowserDialog
The noteworthy properties of the FolderBrowserDialog class are shown in Table 5.11:
Table 5.11: Noteworthy Properties of the FolderBrowserDialog Class Property
Description RootFolder SelectedPath ShowNewFolderButton
Description
Retrieves or sets the descriptive text displayed above the TreeView control in the dialog box Retrieves or sets the root folder where the browsing starts Retrieves or sets the path selected by the user Retrieves or sets a value indicating whether or not the New Folder button appears in the folder browser dialog box
You have already learned about the TreeView control in Chapter 15, Navigation Controls in ASP.NET 4.0.
The Browse For Folder dialog box is supported by the FolderBrowserDialog class. The dialog box also shows the Make New Folder button if the ShowNewFolderButton property is set to True (by default). The Browse For Folder dialog box prompts the user to browse and select an existing folder or create a new one and select it. Note that the FolderBrowserDialog class is used only to allow the user to select folders, not files and virtual folders.
148
In Depth
The Open dialog box is based on the OpenFileDialog class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.CommonDialog System.Windows.Forms.FileDialog System.Windows.Forms.OpenFileDialog
The noteworthy properties of the OpenFileDialog class are given in Table 5.12:
Table 5.12: Noteworthy Properties of the OpenFileDialog Class Property
CheckFileExists Multiselect ReadOnlyChecked SafeFileName SafeFileNames ShowReadOnly
Description
Retrieves or sets a value indicating if the dialog box displays a warning if the user specifies a non-existent file. Retrieves or sets a value signifying whether or not the dialog box allows multiple file selections. Retrieves or sets a value signifying whether or not the read-only check box is selected on the dialog box. Retrieves the file name and extension for the selected file in the dialog box. The file name does not include the path. Retrieves an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path. Retrieves or sets a value signifying whether or not the dialog box displays a read-only check box.
149
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Description
Opens the file selected by the user, with read-only permission. The file is specified by the FileName property. Resets all the options to their default values.
The OpenFileDialog class supports the Open dialog box, which allows you to retrieve the names of files to open. If the Multiselect property is set to True,the users can also select multiple files. The ShowReadOnly property is used to determine if a read-only checkbox appears in the dialog box. The ReadOnlyChecked property indicates whether the read-only checkbox is selected. The Filter property sets the current file name filter string, which determines the file extension choices that appear in the dialog box. The name and path selected by the user is stored in the FileName property of the OpenFileDialog object. You can use the OpenFile() method to open the selected file directly.
The noteworthy properties of the SaveFileDialog class are given in Table 5.14:
150
Description
Retrieves or sets a value specifying whether or not the dialog box asks the user if it should create a file if the user specifies a non-existent file Retrieves or sets a value specifying whether or not the dialog box displays a warning if the user specifies a name that already exists
You can also set the CheckFileExists and CheckPathExists properties to True to check if a specified file or path already exists, or should it be created otherwise.
Description
Opens the file with read/write permission Resets all dialog box options to their default values
The ShowDialog() method is called to display the Font dialog box. This dialog box shows the list boxes for Font, Style, and Size, checkboxes for effects such as Strikeout and Underline, a drop-down list for Script (Script refers to different character scripts that are available for a given fontfor example, Hebrew), and a sample of how the font appears. You can recover these settings using properties of the Font object returned by the Font property.
151
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
The FontDialog class displays a dialog box that lets the user select a font, font style, and size. It returns a Font object in the Font property, and a Color object in the Color property. The class hierarchy for the FontDialog class is as follows:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.CommonDialog System.Windows.Forms.FontDialog
The noteworthy properties of the FontDialog class are given in Table 5.16:
Table 5.16: Noteworthy Properties of the FontDialog Class Property
AllowSimulations
Description
Retrieves or sets a value specifying whether or not the dialog box allows Graphics Device Interface (GDI) font simulations. GDI is responsible for drawing lines, curves, and rendering of fonts. Retrieves or sets a value specifying whether or not the dialog box allows vector font selections. Vector fonts refer to the connection of lines between a series of dots that can be scaled to different sizes. Retrieves or sets a value specifying whether the dialog box displays either both vertical and horizontal fonts or only horizontal fonts. Retrieves or sets the selected font color. Retrieves or sets a value specifying whether or not the dialog box allows the selection of fixed-pitch fonts, which refers to the fonts having every character with the same width. Retrieves or sets the selected font. Retrieves or sets a value specifying whether or not the dialog box specifies an error condition if the user attempts to select a font or style that does not exist. Retrieves or sets the maximum font size a user can select. The default value for font size is 0. Retrieves or sets the minimum font size a user can select. Retrieves or sets a value specifying whether or not the dialog box contains an Apply button. Retrieves or sets a value specifying whether or not the dialog box displays the color choice. Retrieves or sets a value specifying whether or not the dialog box contains controls that allow the user to specify strikethrough, underline, and text color options. Retrieves or sets a value specifying whether or not the dialog box displays a Help button.
AllowVectorFonts
AllowVerticalFonts Color FixedPitchOnly Font FontMustExist MaxSize MinSize ShowApply ShowColor ShowEffects ShowHelp
Description
Resets all dialog box options to default values Shows the dialog box
The only noteworthy event of the FontDialog class is the Apply event, which occurs when the user clicks the Apply button.
152
In Depth
In Figure 5.9, you can use the Color dialog box (by clicking the Define Custom Colors button) to define your own colors with color values and hue, saturation, and luminosity. On the other hand, if you set the AllowFullOpen property to False, the Define Custom Colors button is disabled and the user can select colors only from the predefined colors in the palette. The class hierarchy for the ColorDialog class is as follows:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.CommonDialog System.Windows.Forms.ColorDialog
The noteworthy properties of the ColorDialog class are given in Table 5.18:
Table 5.18: Noteworthy Properties of the ColorDialog Class Property
AllowFullOpen AnyColor Color CustomColors FullOpen ShowHelp SolidColorOnly
Description
Retrieves or sets a value specifying whether or not the user can use the dialog box to define custom colors Retrieves or sets a value specifying whether or not the dialog box displays all available colors in the set of basic colors Retrieves or sets the color selected by the user for the text Retrieves or sets the set of custom colors shown in the dialog box Retrieves or sets a value specifying whether or not the controls used to create custom colors are visible when the dialog box is opened Retrieves or sets a value specifying whether or not a Help button appears in the color dialog box Retrieves or sets a value specifying whether or not the dialog box restrict users to selecting solid colors only and not dithered colors
Description
Resets all the dialog box options to their default values
153
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.19: Noteworthy Methods of the ColorDialog Class Method
ShowDialog() ToString()
Description
Shows the dialog box Gets a string that represents the ColorDialog object
The PrintDocument control is based on the PrintDocument class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Drawing.Printing.PrintDocument
The noteworthy properties of the PrintDocument class are given in Table 5.20:
Table 5.20: Noteworthy Properties of the PrintDocument Class Property
DefaultPageSettings DocumentName OriginAtMargins
Description
Retrieves or sets default page settings for all pages to be printed Retrieves or sets the document name to display while printing the document Retrieves or sets a value specifying whether or not the position of a graphics object associated with a page is located just inside the user-specified margins or at the top-left corner of the printable area of the page
154
Description
Retrieves or sets the print controller for guiding the printing process Retrieves or sets the printer that prints the document
Description
Starts the printing operation Gives information about the print document in a string form
Description
Occurs when the Print() method is called and before the first page of the document is printed Occurs when the last page of the document has been printed Occurs when the output to print for the current page is needed Occurs immediately before each PrintPage event
The PrinterSettings class can also be used to configure how a document is printed, by specifying the printer to be used, number of copies to print, and the page range to print. The hierarchy of the PrinterSettings class is as follows:
System.Object System.Drawing.Printing.PrinterSettings
The static/shared property (which can be used with the class name, without an object, such as PrinterSettings.InstalledPrinters) of the PrinterSettings class is given in Table 5.23:
Table 5.23: Noteworthy Static/Shared Property of the PrinterSettings Class Property
InstalledPrinters
Description
Returns the names of all printers installed on the computer
Description
Set to true if the printer supports double-sided printing Retrieves whether or not the printed document is collated Retrieves the number of copies of the document to be printed Retrieves the default page settings for the current printer Retrieves the printer settings for double-sided printing Retrieves the page number of the first page to be printed Specifies whether or not the printer is a plotter Specifies whether or not the printer is valid
155
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.24: Noteworthy Properties of the PrinterSettings Class Property
LandscapeAngle MaximumCopies MaximumPage MinimumPage PaperSizes PaperSources PrinterName PrinterResolutions PrintRange PrintToFile SupportsColor ToPage
Description
Specifies the angle of the paper, in degrees, used for printing in landscape orientation Specifies the maximum number of copies that the printer allows you to print at one time Retrieves the maximum FromPage property or ToPage property that can be selected in a PrintDialog Retrieves the minimum FromPage property or ToPage property that can be selected in a PrintDialog Specifies the paper sizes that are supported by this printer Specifies the paper source trays that are available on the printer Retrieves the name of the printer to be used Retrieves resolutions supported by the printer Retrieves the page numbers to be printed, as specified by the user Retrieves a value indicating whether or not the printing output is sent to a file instead of a port Returns whether or not this printer supports color printing Retrieves the number of the last page to be printed
Description
Retrieves a Graphics object that contains printer information Creates a copy of the PrinterSettings class
156
In Depth
The Page Setup dialog box is supported by the PageSetupDialog class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.CommonDialog System.Windows.Forms.PageSetupDialog
The noteworthy properties of the PageSetupDialog class are given in Table 5.26:
Table 5.26: Noteworthy Properties of the PageSetupDialog Class Property
AllowMargins AllowOrientation AllowPaper AllowPrinter Document EnableMetric
Description
Retrieves or sets a value specifying whether or not the margins section of the dialog box is enabled. Retrieves or sets a value specifying whether or not the orientation section of the dialog box (landscape or portrait) is enabled. Retrieves or sets a value specifying whether or not the paper section of the dialog box (paper size and paper source) is enabled. Retrieves or sets a value specifying whether or not the Printer button is enabled. Retrieves or sets a value specifying the PrintDocument object which gets the page settings. Retrieves or sets a value specifying whether or not the margin settings, when displayed in millimeters, should be automatically converted to and from hundredths of an inch. Retrieves or sets a value specifying the minimum margins the user is allowed to select. The value is measured in hundredths of an inch. Retrieves or sets a value specifying the page settings to be modified. Retrieves or sets the printer settings that are modified when the user clicks the Printer button in the dialog box. Retrieves or sets a value indicating whether or not the Help button is visible. Retrieves or sets a value specifying whether or not the Network button is visible.
Description
Resets all dialog box options to their default values Shows the dialog box
157
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
The noteworthy properties of the PrintPreviewControl class are given in Table 5.28:
Table 5.28: Noteworthy Properties of the PrintPreviewControl Class Property
AutoZoom Columns Document Rows StartPage UseAntiAlias Zoom
Description
Retrieves or sets a value that indicates whether or not the Zoom property is set automatically Retrieves or sets the number of pages displayed horizontally Retrieves or sets a value indicating the document to be previewed Retrieves or sets the number of pages displayed vertically Retrieves or sets the page number of the upper left page Retrieves or sets a value specifying whether or not printing uses the anti-aliasing features of the operating system Retrieves or sets the zoom level of the print preview
Description
Refreshes the preview of the document Resets the background color of the control to the color of the application workspace, which is the default color Resets the foreground color of the control to White, which is the default color Shows the PrintPreviewControl control to the user
158
Description
Occurs when the start page changes Occurs when the value of the Text property changes
The Print preview dialog box is supported by the PrintPreviewDialog class, which has the following class hierarchy:
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ScrollableControl System.Windows.Forms.ContainerControl System.Windows.Forms.Form System.Windows.Forms.PrintPreviewDialog
The noteworthy properties of the PrintPreviewDialog class are given in Table 5.31:
Table 5.31: Noteworthy Properties of the PrintPreviewDialog Class Property
AcceptButton ControlBox Document FormBorderStyle HelpButton
Description
Retrieves or sets the button that is automatically clicked when the user presses the ENTER key Retrieves or sets a value specifying whether or not a control box is displayed in the title bar of the Windows Form Retrieves or sets the document to preview Retrieves or sets the border style of the form Retrieves or sets a value specifying whether or not a Help button should be displayed in the control box of the form
159
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.31: Noteworthy Properties of the PrintPreviewDialog Class Property
MaximizeBox MaximumSize MinimizeBox MinimumSize PrintPreviewControl ShowInTaskbar StartPosition TopMost
Description
Retrieves or sets a value specifying whether or not the Maximize button is displayed in the title bar of the form Retrieves or sets the maximum size the form can be resized to Retrieves or sets a value indicating whether or not the Minimize button is displayed in the caption bar of the form Retrieves the minimum size the form can be resized to Retrieves the data contained in this form Retrieves whether or not the form is displayed in the Windows taskbar Retrieves or sets the starting position of the dialog box at run time Retrieves or sets a value specifying whether or not the form should be displayed as your applications topmost form
The main property of the dialog box is Document, which sets the document to be previewed. The document to be previewed must be an object of the PrintDocument class. The Print preview dialog box is based on the PrintPreviewControl object. You can also use PrintPreviewControl objects directly to create your own custom print preview dialog boxes.
160
In Depth
The noteworthy properties of the PrintDialog class are given in Table 5.32:
Table 5.32: Noteworthy Properties of the PrintDialog Class Property
AllowCurrentPage AllowPrintToFile AllowSelection AllowSomePages Document PrinterSettings PrintToFile ShowHelp ShowNetwork
Description
Retrieves or sets a value specifying whether or not the Current Page option button is displayed. The Current Page option button prints the current page. Retrieves or sets a value specifying whether or not the Print to file check box is enabled. Retrieves or sets a value specifying whether or not the Selection option button is enabled. The Selection option prints the selected text on a page. Retrieves or sets a value specifying whether or not the Pages option button is enabled. Retrieves or sets a value specifying the PrintDocument control used to obtain PrinterSettings. Retrieves or sets the printer settings that the dialog box modifies. Retrieves or sets a value specifying whether or not the Print to file check box is selected. Retrieves or sets a value specifying whether or not the Help button is displayed. Retrieves or sets a value specifying whether or not the Network button is displayed.
Description
Resets all dialog box options to their default values Displays the dialog box
Set the Document property of a PrintDialog object with the help of a PrintDocument object. In the Print dialog box, a document is printed by setting the PrinterSettings property of a PrintDialog object, which indicates the number of copies to be printed. Finally, the Print() method of the PrintDocument object prints the document. Lets now move on to the Immediate Solutions section, where we implement the concepts explained in the In Depth section.
161
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Immediate Solutions
Using the ToolStrip Control
As mentioned previously, a ToolStrip control is used to create custom toolbars to support advanced user interface and layout features. Lets understand some properties and events of the ToolStrip control by creating an application, named ToolStripSample (also available on the CD-ROM). Set the Text property of the Form1 form to ToolStripSample. The form contains a ToolStrip control and a Button control. Lets perform the following tasks with the ToolStrip control:
Adding items to the ToolStrip control Handling the Click event of the ToolStripButton control Setting the tool tips for ToolStrip items Using the TAB key to Navigate through the ToolStrip items
2.
Select the type of items, as shown in Table 5.34, from the drop-down list beside the Add button and click the Add button. Similarly, items can be removed from the list by first selecting the item from the list and then clicking the Remove button that is denoted with a cross mark in the dialog box. The text for an item can also be set in the Items Collection Editor dialog box using the Text property. An image for the item can be added from the application resources or directly from a file using the Image property. To set the style for the button, use the DisplayStyle property and specify the arrangement of the text and image on the items using the TextImageRelation property. You can add one of the following items to a tool strip from the Items Collection Editor dialog box:
162
Immediate Solutions
3.
ToolStripButtonRepresents a normal button ToolStripLabelRepresents a non-selectable ToolStripItem that renders text, images, and hyperlinks ToolStripSeparatorRepresents a line which is used to group items of a ToolStrip control ToolStripComboBoxRepresents a combo box in a ToolStrip control ToolStripTextBoxRepresents a text box in a ToolStrip control that allows the user to enter text ToolStripSplitButtonRepresents a combination of a standard button on the left and a dropdown button on the right
ToolStripDropDownButtonRepresents a button that when clicked displays a drop-down list from which the user can select a single item Set the property and value of each item in the ToolStrip control, as given in Table 5.34:
Item Type Property
DisplayStyle
Table 5.34: Items to be Added to the ToolStrip Control Item Name Value
ImageAndText Simple [Set an image to the Image property] ImageBeforeText Text Toggle True Text Split [Add two MenuItems to DropDownItems property] the
toolStripButton1
Button
toolStripButton2
Button
toolStripSplitButton1
SplitButton
[Set an image to the Image property] Copy [Set an image to the Image property] Paste Text Drop Down [Add four MenuItems DropDownItems property] Red Blue Green Pick Color [Nothing] Verdana Tahoma to the
toolStripDropDownButton1
DropDownButton
Text DropDownItems toolStripMenuItem3: Text toolStripMenuItem4: Text toolStripMenuItem5: Text toolStripMenuItem6: Text
toolStripSeparator1 toolStripComboBox1
Separator ComboBox
[Nothing] Items
163
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls Table 5.34: Items to be Added to the ToolStrip Control Item Name Item Type Property
Text toolStripSeparator2 toolStripTextBox1 toolStripSeparator3 toolStripProgressBar1 toolStripSeparator4 Separator TextBox Separator ProgressBar Separator [Nothing] Text [Nothing] Value [Nothing]
Value
Select [Nothing] Tool Strip Text Box [Nothing] 60 [Nothing]
4.
Press the F5 key on the keyboard to execute the application. Figure 5.16 shows the output of the application:
Now, lets explain how to handle the Click event by a ToolStripControl in the next section.
2.
Press the F5 key on the keyboard to execute the application. When the form appears, click the Simple button in the ToolStrip control. A message box appears with a message indicating that the button has been clicked, as shown in Figure 5.17:
164
Immediate Solutions
In the ToolStripSample application, perform the following steps for setting tool tips for the items in a ToolStrip control: 1. Set the property and value of the items in the ToolStrip control, as given in Table 5.35:
Properties
AutoToolTip ToolTipText ToolTipText
Value
false Colors Font
2.
Press the F5 key on the keyboard to execute the application; and when the form appears, move the cursor over the combo box. A tool tip, named Font, appears on the combo box item in the ToolStrip control, as shown in Figure 5.18:
Figure 5.18: Displaying the Tool Tip for the ToolStrip Combo Box Item
Adding menu items to a MenuStrip control Adding submenus Disabling and enabling menu items Hiding and displaying menu items Displaying checkmarks on menu items Displaying separator between menu items Setting access keys to menu items Setting shortcut keys to menu items
165
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Adding images to menu items Creating context menus Associating a context menu with another controls Adding text boxes and combo boxes to menus and context menus Linking menu items with the ToolStrip button Lets start by adding the menu items to a MenuStrip control.
You can make the menu items perform some actions by creating event handlers for handling their Click event in the Code Editor. 4. Double-click the Exit menu item of the File menu and modify the code of the Click event of exitToolStripMenuItem, as shown in the following code snippet:
private void exitToolStripMenuItem_Click(object sender, System.EventArgs e) { this.Close(); }
In the preceding code snippet, the Close() method is used to exit the program. 5. Press the F5 key on the keyboard to execute the application and the menu appears on the Form1 form. Now, click the Exit menu item to close the application. Lets now see how to add submenus to these menu items.
Adding Submenus
In the previous topic, you learn how to add menu items to a MenuStrip control. You can also create submenus, which involves adding menu items within another menu item. When a menu item has a submenu, a right pointing arrow appears in that menu item at run time. Clicking that arrow opens the submenu, displaying additional menu items. Note that submenus can also have sub submenus, which can further have other submenus as well. To add submenus to the New menu item of the File menu, perform the following steps: 1. 2. Click the New menu item. It opens a Type Here textbox to the right of the New menu item. Click the Type Here textbox and enter the caption for the submenu item as Item1, as shown in Figure 5.20:
166
Immediate Solutions
3. 4.
Similarly, add one more submenu to the New menu item as Item2. Now in the same way, add two submenus Item3 and Item4 to the Item2 submenu. Double-click the Item1 submenu and modify the code of the Click event of item1ToolStripMenuItem, as shown in the following code snippet:
private void item1ToolStripMenuItem_Click(object sender, System.EventArgs e) { MessageBox.Show("You clicked " + sender.ToString()); }
In the preceding code snippet, the Show() method of the MessageBox class is used to display a message to the user. 5. Press the F5 key on the keyboard to execute the application. When the form appears, click File New Item2 and the output is displayed, as shown in Figure 5.21:
6.
Click the Item1 submenu, a message box is displayed, as shown in Figure 5.22:
2. 3.
Press the F5 key on the keyboard to execute the application. When the form appears, click the Item3 submenu. A message box appears displaying the message, Disabling Spell Check menu item. Click the OK button to close the message box. The Spell Check menu item gets disabled (Figure 5.23).
167
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
4.
Enable the menu item by setting the Enabled property of the menu item to true. To do so, double-click the Item2 submenu in the design mode of the Form1 form and modify the code of the Click event of item2ToolStripMenuItem, as shown in the following code snippet:
private void item2ToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Enabling Spell Check menu item"); spellCheckToolStripMenuItem.Enabled = true; }
5.
Press the F5 key on the keyboard to execute the application. When the form appears, first disable the Spell Check menu item by clicking the Item3 submenu and then click the Item2 submenu to enable the Spell Check menu item. A message box appears, as shown in Figure 5.23:
Figure 5.23: Displaying a Message Box on the Selection of the Item2 Submenu
6.
Click the OK button to close the message box. The Spell Check menu item gets enabled, as shown in Figure 5.24:
2. 3.
Press the F5 key on the keyboard to execute the application. When the form appears, select the Item4 submenu. A message box appears displaying the message, Hiding Item4. Click the OK button to close the message box. The Item4 submenu is hidden, as shown in Figure 5.25:
168
Immediate Solutions
4.
Display the hidden submenu by setting the Visible property of the submenu to true. Modify the code of the Click event of Item1 submenu, as shown in the following code snippet:
private void item1ToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked " + sender.ToString()); // code to display item 4 item4ToolStripMenuItem.Visible = true; MessageBox.Show("Displaying Item 4"); }
5.
6.
Press the F5 key on the keyboard to execute the application. When the form appears, first hide the Item4 submenu and then click the Item1 submenu. A message box appears displaying the You clicked Item1 message. After pressing the OK button, the second message box appears with the message, Displaying Item4. Click the OK button to close the message box. The Item4 submenu is displayed in the menustrip1 control.
2.
Press the F5 key on the keyboard to execute the application. When the form appears, the Spell Check menu item is unchecked. Select the menu and a checkmark appears in front of it, as shown in Figure 5.26:
If you select the menu item again, the checkmark disappears from the Spell Check menu item.
169
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
A menu separator is added before the Spell Check menu item, as shown in Figure 5.27:
Figure 5.27: Adding a Separator between the New and Spell Check Menu Items
Press the F5 key on the keyboard to execute the application. When the form appears, click the File menu, you can see the separators between the New and Spell Check menu items. Lets now learn to set the access keys for menu items.
2.
2. 3.
170
Immediate Solutions
2.
Press the F5 key on the keyboard to execute the application and the output is displayed, as shown in Figure 5.30:
When the user presses the CTRL+E keys, the Exit menu item gets activated. You can also assign a short cut key to to a tool strip menu item by using the members of the ShortcutKeys enumeration. The following code snippet shows how to assign a short cut key to a tool strip menu item:
ToolStripMenuItem.ShortcutKeys = Shortcut.CtrlE;
You need to use the preceding code snippet in the Load event of a form
Shortcuts select their corresponding menu items even if no menu is open at the time. If you want to make sure the user must first open the items menu, use access keys instead.
171
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
2. 3. 4. 5.
Select the Project resource file radio button and click the Import button, the Open dialog box appears from where you can add images to your project resource file. Select the images and click the OK button to add the images to the project resource file. The images appear in the Select Resource dialog box. In this case, the NEW.jpg image is added. Select the NEW.jpg image from the list and click the OK button. Press the F5 key on the keyboard to execute the application. When the form appears, the image appears in front of the New menu item, as shown in Figure 5.32:
Some images have a background that you may not want to display when the user selects the menu option. To make this background disappear, set the background color of the image to Transparent using the ImageTransparentColor property.
2.
Double-click the Cut menu item and modify the code of the Click event of cutToolStripMenuItem, as shown in the following code snippet:
private void cutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked the Cut menu item"); }
In the code, at the Click event of the Cut menu item, a message box is displayed. 3. Double-click the Copy menu item and modify the code of the Click event of copyToolStripMenuItem, as shown in the following code snippet:
private void copyToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked the Copy menu item"); }
In the code, at the Click event of the Copy menu item, a message box is displayed. 4. Double-click the Paste menu item and modify the code of the Click event of pasteToolStripMenuItem, as shown in the following code snippet:
172
Immediate Solutions
private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked the Paste menu item"); }
In the code, at the Click event of the Paste menu item, a message box is displayed. 5. Press the F5 key on the keyboard to execute the application. Now, if you right-click the form, you do not see any context menu. This is because we have just defined menu items for the ContextMenuStrip control. To display the context menu, you need to associate the ContextMenuStrip control with either any Windows Forms control or with the Windows Form.
In the code, the Cut() method of the text box moves the selected text in the text box to the clipboard. 4. Add the following highlighted code in the Click event of the Copy menu item:
private void copyToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked the Copy menu item"); textBox1.Copy(); }
In the code, the Copy() method of the text box copies the selected text in the text box to the clipboard. 5. Add the following highlighted code in the Click event of the Paste menu item:
private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You clicked the Paste menu item"); textBox1.Paste(); }
In the code, the Paste() method of the text box replaces the selected text in the text box with the contents in the clipboard. 6. Press the F5 key on the keyboard to execute the application. Now enter some text in the text box, select it, and right-click the text box, the context menu appears, as shown in Figure 5.34:
Now, you can select any of the items from the context menu and perform the respective task.
173
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Adding Text Boxes and Combo Boxes to Menus and Context Menus
Apart from hosting ToolStripMenuItem objects, MenuStrip can host a number of other standard menu item objects, such as ToolStripComboBox, ToolStripSeparator, and ToolStripTextBox objects. You can add any of these items to the menu using the Type Here combo box. Perform the following steps to add a text box and a combo box to the MenuStrip control: 1. 2. Add an Edit menu to the MenuStrip control. Then, add a Replace With menu item to the Edit menu. Add a text box beside the Replace With option by selecting the TextBox option from the Type Here combo box, as shown in Figure 5.35:
Add a Font menu item under the Replace With option and add combo box below the Font menu item by selecting the ComboBox option from the Type Here combo box. 4. Select the Items property of the combo box. A String Collection Editor dialog box appears. 5. Add these seven items in the dialog box Arial, Calibri, Comic Sans MS, Impact, Tahoma, Times New Roman, and Verdana and set the Text property of the combo box to Select. All these items work like the standard ToolStripMenuItem objects only, but with added advantages. For example, in the menu that opens when you click the Replace With submenu, you can type something in the text box and press the Enter key. The item that you have typed is automatically added to the menu item. 6. Modify the code of the SelectedIndexChanged event of toolStripComboBox1 to set the selected font on the newly added item, as shown in the following code snippet:
private void toolStripComboBox1_SelectedIndexChanged(object sender, System.EventArgs e) { toolStripTextBox1.Font = new Font(toolStripComboBox1.SelectedItem.ToString(), (float)(Font.Size), Font.Style); }
3.
7. 8.
Press the F5 key on the keyboard to execute the application, when the form appears, select the Edit Replace With option and enter the text C# 2010 in the text box beside the Replace With option. Select Comic Sans MS option from the combo box in the Edit menu, the text entered in the text box changes to Comic Sans MS, as shown in Figure 5.36:
Similarly, you can also add a text box and a combo box to the context menu. Lets perform the following steps to do so: 1. Add a text box to the context menu below the Paste option by selecting the TextBox option from the Type Here combo box, as shown in Figure 5.37:
174
Immediate Solutions
2. 3. 4. 5.
Add a combo box to the context menu below the text box by selecting the ComboBox option from the Type Here combo box. Select the Items property of the combo box. A String Collection Editor dialog box appears. Add these seven items in the dialog box Arial, Calibri, Comic Sans MS, Impact, Tahoma, Times New Roman, and Verdana and set the Text property of the combo box to Select Font. Modify the code of the SelectedIndexChanged event of toolStripComboBox2 to set the selected font on the text box font, as shown in the following code snippet:
private void toolStripComboBox2_SelectedIndexChanged(object sender, System.EventArgs e) { textBox1.Font = new Font(toolStripComboBox2.SelectedItem.ToString(), (float)(Font.Size), Font.Style); }
6.
7.
Press the F5 key on the keyboard to execute the application, when the form appears, enter the text Welcome to the world of .NET. Enjoy learning Visual C# and right-click on the Form1 form (Figure 5.38). Type Undo in the text box of the context menu, the menu item is added in the context menu. In addition, also select Impact option from the combo box of the context menu, the font of the text in the text box changes, as shown in Figure 5.38:
Figure 5.38: Adding Combo Box and Text Box Controls to a ContextMenu Control
175
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
In the MenuStripandContextMenuStripSample application, perform the following steps to link menu items with the ToolStrip button: 1. 2. Drag and drop a ToolStrip control to the Form1 form. Add the items, given in Table 5.36, to the ToolStrip control and set the properties and values of the ToolStrip items, as given in Table 5.36:
Table 5.36: Items to be Added to the ToolStrip Control Item Name
toolStripButton1
Item Type
Button
Property
DisplayStyle Image ToolTipText
Value
Image [Set an image to the Image property] Cut Image [Set an image to the Image property] Copy Image [Set an image to the Image property] Paste
toolStripButton2
Button
toolStripButton3
Button
3.
Add three menu items to the Edit menu, Cut, Copy, and Paste; and modify the code of their respective Click events, as shown in Listing 5.1: Listing 5.1: Showing the Code of the Cut, Copy, and Paste Menu Items
private void CopyToolStripMenuItem1_Click(object sender, System.EventArgs e) { textBox1.Copy(); } private void PasteToolStripMenuItem1_Click(object sender, System.EventArgs e) { textBox1.Paste(); } private void cutToolStripMenuItem1_Click(object sender, EventArgs e) { textBox1.Cut(); }
4. Modify the code of the Click events of the button items of the ToolStrip control, as given in Listing 5.2: Listing 5.2: Showing the Code of the Cut, Copy, and Paste Button Items of the ToolStrip Control
private void toolStripButton1_Click(object sender, EventArgs e) { pasteToolStripMenuItem1.PerformClick(); } private void toolStripButton2_Click(object sender, EventArgs e) { copyToolStripMenuItem1.PerformClick(); } private void toolStripButton3_Click(object sender, EventArgs e) { cutToolStripMenuItem1.PerformClick(); }
5.
Press the F5 key on the keyboard to execute the application. When the form appears, type Hello World in the text box. Select the entire text in the text box and click the Copy icon on the ToolStrip control. Then paste the text anywhere in the text box by clicking on the Paste icon on the ToolStrip control, as shown in Figure 5.39:
176
Immediate Solutions
Figure 5.39: Displaying the Linking of Menu Items with ToolStrip Buttons
The Copy button on the ToolStrip control corresponds to the Copy item in the Edit menu, and clicking that button is equivalent to clicking the Copy menu item. This application demonstrates that a tool strip is a shortcut to the most frequently used menu items. Lets now learn to implement the StatusStrip Control.
177
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
3. 4.
Add a StatusLabel item to it by selecting the StatusLabel item from the combo box and clicking the Add button. Modify the code of the TextChanged event of textBox1, as shown in the following code snippet:
private void textBox1_TextChanged(object sender, EventArgs e) { string[] str = textBox1.Text.Split(' '); toolStripStatusLabel1.Text = ("Words: " + str.Length + ", " + "Characters (with spaces): " + textBox1.TextLength);
In the preceding code snippet, the Text property of the StatusLabel item is used to set the text. Whenever the user enters any text in the text box, the number of characters and words are recorded in the status strip of the form. 5. Press the F5 key on the keyboard to execute the application and the output is shown in Figure 5.41:
Now, we have created something similar to a Word processor. If you notice the status bar of Microsoft Word, it displays the number of pages and words in its status bar. Lets now see how to add an icon to the StatusStrip control.
178
Immediate Solutions
Add the Paste item to the SplitButton item in the same manner as we did for the Copy item. Modify the code of the Click events of toolStripMenuItem1 and toolStripMenuItem2, as shown in Listing 5.3: Listing 5.3: Showing the Code of the Click Events of toolStripMenuItem1 and toolStripMenuItem2
private void toolStripMenuItem1_Click(object sender, EventArgs e) { textBox1.Copy(); } private void toolStripMenuItem2_Click(object sender, EventArgs e) { textBox1.Paste(); }
5. 6.
7.
Press the F5 key on the keyboard to execute the application. When the form appears, type the Welcome to Visual C# 2010 text in the text box. Select the entire text in the text box and then select the Copy option from the Edit split button on the StatusStrip control. Paste the text anywhere on the text box by clicking the Paste option from the Edit split button on the StatusStrip control, as shown in Figure 5.43:
Similarly, you can add a progress bar to the StatusStrip control by performing the following steps: 1. Add a ProgressBar item to the StatusStrip control by selecting the ProgressBar item from the combo box and clicking on the Add button.
179
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
2. 3.
Drag and drop a Button control in the Form1 form with the Text property set as Start. Double-click the button and modify the code of the Click event of button1, as shown in the following code snippet:
private void button1_Click(object sender, EventArgs e) { int x; toolStripProgressBar1.Minimum = 1; toolStripProgressBar1.Maximum = 100000; toolStripProgressBar1.Value = 1; toolStripProgressBar1.Step = 1; for (x = 1; x < 100000; x++) { toolStripProgressBar1.PerformStep(); } textBox1.Text = "Welcome to C# 2010"; }
4.
Press the F5 key on the keyboard to execute the application and click the Start button, the output is displayed, as shown in Figure 5.44:
The status strip covers almost all the items that can possibly be added on a status bar. Lets now learn to implement the dialog box controls.
180
Immediate Solutions
Lets create an application named FolderBrowserDialogSample (also available on the CD-ROM). In this application, perform the following steps to use the FolderBrowserDialog control: 1. Drag and drop the controls, given in Table 5.37, to the Form1 form and set their properties and values, as given in Table 5.37:
Property
Anchor AutoSize BorderStyle Text Button Text Anchor Button ListBox FolderBrowserDialog Text Anchor Description
Value
Top, Left, Right False Fixed3D [Blank] Browse Top, Right Find Files Top, Bottom, Left, Right Select Folder to Search In
2.
Double-click the button1 control and modify the code of the Click event of button1, as shown in the following code snippet:
private void button1_Click(object sender, EventArgs e) { folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer; folderBrowserDialog1.SelectedPath="D:\\Books"; if (folderBrowserDialog1.ShowDialog()==DialogResult.OK) { label1.Text = folderBrowserDialog1.SelectedPath; } }
In the preceding code snippet, a FolderBrowserDialog control, named folderBrowserDialog1, is used with its two properties RootFolder and SelectedPath. The RootFolder property is used to specify the root path as Environment.SpecialFolder.MyComputer; and the SelectedPath property is used to specify a directory path as D:\\Books. If the OK button of the folderBrowserDialog1 control is clicked, the directory path is assigned to a Label control, named label1, by using its Text property. 3. Add a reference of the Microsoft.VisualBasic assembly to the application and add the following namespaces to the application:
using Microsoft.VisualBasic.FileIO; using System.Collections.ObjectModel;
4.
Double-click the button2 control and modify the code of the Click event of button2, as shown in the following code snippet:
private void button2_Click(object sender, EventArgs e) { ReadOnlyCollection<string> files = null; files = FileSystem.GetFiles(label1.Text); listBox1.DataSource = files; }
In the preceding code snippet, an object of the ReadOnlyCollection<string> generic class is used to store the name of the files returned by the GetFiles() method of the FileSystem class. These files are later stored in a list box. 5. Press the F5 key on the keyboard to execute the application. When the form appears, click the Browse button, the Browse For Folder dialog box appears, as shown in Figure 5.45:
181
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Figure 5.45: Displaying the Browse For Folder Dialog Box with Root Folder Set to Computer
In Figure 5.45, you can see that the Browse For Folder dialog box lists only the subdirectories of Computer. When you select a folder from which you want to retrieve the files, the selected folder path appears on the label, as shown in Figure 5.46:
6. Click the Find Files button. All the files within that folder appear in the list box (Figure 5.46). Lets now see how the OpenFileDialog control works.
3.
182
Immediate Solutions
4.
Modify the code of the Click event of button1 to determine the file that a user wants to open from the FileName property and load the corresponding image into the picture box, as shown in the following code snippet:
private void button1_Click(object sender, EventArgs e) { openFileDialog1.InitialDirectory = "D:\\Pictures"; if (openFileDialog1.ShowDialog() != DialogResult.Cancel) { pictureBox1.Image = Image.FromFile(openFileDialog1.FileName); } }
5.
Press the F5 key on the keyboard to execute the application. When the form appears, click the Load Image button. An Open dialog box appears, as shown in Figure 5.47:
Figure 5.47: The Open Dialog Box after clicking the Load Image Button
6.
Select an image and it appears in the picture box, as shown in Figure 5.48:
183
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
1. 2. 3. 4. 5. 6.
Set the Text property of the Form1 form to Save File Dialog Sample. Drag and drop a Label control, a TextBox control, a Button control, and a SaveFileDialog control to the form. Set the Text property of the Label control to Enter text to save. Set the text box to multiline text box by setting its Multiline property to true. Set the Text property of the Button control to Save. Double-click the Save button and modify the code of the Click event of button1, as shown in the following code snippet:
private void button1_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt*"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText(saveFileDialog1.FileName, textBox1.Text, true); } }
In the preceding code snippet, with the Filter property of the SaveFileDialog control, the dialog box is set to display text file types having .txt extensions only. The WriteAllText() method of the FileSystem class writes text to a file and takes three parameters, which are as follows: Name of the file Text to be saved Boolean value (true or false), which allows a user to append the file
You can use the CreatePrompt property to display a prompt asking the user if a file that does not exist should be created, and the OverwritePrompt property to ask the user whether an existing file should be overwritten.
7. 8.
Add a reference of the Microsoft.VisualBasic assembly to the application. Press the F5 key on the keyboard to execute the application. When the form appears, type the Welcome to Visual C# 2010 text in the text box and click the Save button to save the text as a .txt file. A Save As dialog box appears, as shown in Figure 5.49:
Figure 5.49 displays the Save as type as TXT Files (*.txt*), which we have set in the code using the Filter property.
184
Immediate Solutions
9.
Type a name for the file to be saved, and click the Save button (Figure 5.49). The File is saved on the Desktop with the name entered in the File name text box. In this case, it is saved with the Welcome.txt file name.
You can set the title of a dialog box using the Title property.
5.
In the preceding code snippet, the Font and Color properties of the FontDialog control is used to set the font and its color selected by the user on the text set in the rich text box. 6. Press the F5 key on the keyboard to execute the application. When the form appears, click the Select Font button. A Font dialog box appears, as shown in Figure 5.50:
7.
Select the font, font style, size, effects, and color of the font from the Font dialog box.
185
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
8.
Click the OK button and the new font and color is assigned to the text in the rich text box, as shown in Figure 5.51:
In the preceding code, the color chosen by the user in the Color dialog box is set to the BackColor property of the label using the Color property of the ColorDialog control. 6. Press the F5 key on the keyboard to execute the application and when the form appears, click the Choose Color button. A Color dialog box appears, as shown in Figure 5.52:
186
Immediate Solutions
7.
Select a color and click the OK button (Figure 5.52). The selected color is applied to the background color for the label, as shown in Figure 5.53:
The labels original text Change my color!!! is also being changed to Heres my new color!, as shown in Figure 5.53. Lets now see how you can print your document using the various printing controls.
The PrintDocument control The PageSetupDialog control The PrintPreviewControl control The PrintPreviewDialog control The PrintDialog Control
187
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
ColorRetrieves a value indicating whether the page should be printed in color LandscapeRetrieves a value indicating whether the page is printed in landscape or portrait orientation Margins Retrieves the margins for this page PaperSize Retrieves the paper size for the page PaperSource Retrieves the pages paper source PrinterResolution Retrieves the printer resolution for the page PrinterSettings Retrieves the printer settings associated with the page You can let the user display a Page Setup dialog box in the PrintingSample application, and record the new settings in the PrintDocument object. To do so, lets perform the following steps:
1. 2. 3. 4.
Set the Text property of the Form1 form to Printing Sample. Drag and drop a MenuStrip control, a PrintDocument control, and a PageSetupDialog control to the form. Add a File menu to the MenuStrip control, and a Page Setup menu item to the File menu. Double-click the Page Setup menu item and modify the code of the Click event of menu item, as shown in the following code snippet::
private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e) { pageSetupDialog1.Document = printDocument1; pageSetupDialog1.PrinterSettings = printDocument1.PrinterSettings; pageSetupDialog1.PageSettings = printDocument1.DefaultPageSettings; if (pageSetupDialog1.ShowDialog() == DialogResult.OK) { printDocument1.PrinterSettings = pageSetupDialog1.PrinterSettings; printDocument1.DefaultPageSettings = pageSetupDialog1.PageSettings; } }
4.
Press the F5 key on the keyboard to execute the application. When the form appears, click the File Page Setup option. A Page Setup dialog box appears, as shown in Figure 5.54:
After setting the various options for page setting in the Page Setup dialog box, it is preferred to preview the document before printing. There are two options the PrintPreviewControl control and the PrintPreviewDialog control. Lets see each of these in detail.
188
Immediate Solutions
3.
4. 5.
Add a Custom Print Preview menu item to the File menu of Form1. Double-click the Custom Print Preview menu item in the design mode and modify the code of the Click event of menu item, as shown in the following code snippet:
private void customPrintPreviewToolStripMenuItem_Click(object sender, EventArgs e) { Form2 preview = new Form2(); preview.printPreviewControl1.Document = printDocument1; preview.Show(); }
Till now, you have set a PrintPreviewControl control to preview a document. However, a document also needs to be set for preview. 6. Modify the code in the Form2.cs file to set a document for printing, as shown in Listing 5.4: Listing 5.4: Showing the Code to Set a Document for Printing
int pageNumber = 0; private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { pageNumber = 0; } private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { pageNumber = pageNumber+1; switch (pageNumber) { case 1: { e.Graphics.FillRectangle(Brushes.Red, new Rectangle(200, 200, 500, 500)); e.HasMorePages = true; break; } case 2: { e.Graphics.FillRectangle(Brushes.Blue, new Rectangle(200, 200, 500, 500)); e.HasMorePages = false; break; } } }
189
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
This application does not print selected ranges of pagesit just prints the whole document. If you want to handle print ranges, please refer to the PrintDocument.PrinterSettings.PrintRange property, which holds the range of pages to be printed.
7.
Press the F5 key on the keyboard to execute the application. Select the Custom Print Preview option from the File menu in Form1. You see the Printing Preview Control window, as shown in Figure 5.55:
If you want to print some text, you should call the DrawString() method of the Graphics object. Lets see the next control for previewing a document, the PrintPreviewDialog control.
4.
Press the F5 key on the keyboard to execute the application. Select the Print Preview option from the File menu in Form1. You see the Printing preview window, as shown in Figure 5.56:
190
Immediate Solutions
After previewing the document, in the next section you learn to print the document.
The PrinterSettings property of the control should be set or else an exception is thrown. 4. Press the F5 key on the keyboard to execute the application. Select the Print option from the File menu in Form1. You see the Print dialog box, as shown in Figure 5.57:
191
Chapter 5: Windows Forms Controls: ToolStrip, MenuStrip, ContextMenuStrip, StatusStrip, and Dialog Box Controls
Summary
In this chapter, you have learned about various Windows Forms controls, such as ToolStrip, MenuStrip, OpenFileDialog, and PrintDialog. The chapter has started by exploring the toolbars and menus controls and classes, which include the ToolStrip and MenuStrip controls, and the ToolStripItem and ToolStripMenuItem classes. Next, you have learned about the ContextMenuStrip control to create a short cut menu for the right mouse click on a control; and the StatusStrip control to create status bar showing the status of an application. Then, you have learned about various dialog box controls, such as SaveFileDialog and ColorDialog, to perform common Windows tasks related to opening or saving of a file or selecting a color for your text. You have also learned about the controls related to the process of printing a document. These controls include PrintDocument, PageSetupDialog, PrintPreviewControl, PrintPreviewDialog, and PrintDialog. In the next chapter, you learn about various validation controls, such as RequiredFieldValidator, CompareFieldValidator, RangeValidator, RegularExpressionValidator, CustomValidator, and ValidationSummary.
192