1. Trang chủ
  2. » Công Nghệ Thông Tin

Manning Windows Forms Programming (phần 10) ppsx

50 370 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 601,3 KB

Nội dung

416 CHAPTER 13 TOOLBARS AND TIPS with the parent toolbar. Image lists are used by a number of Windows Forms controls to manage the images displayed or available within the control. As a result, we will hold off on creating our toolbar buttons until section 13.3 in order to take a look at this rather important construct. 13.2 IMAGE LISTS There are a number of controls that require one or more images in order to display their contents. Often, the requirement is for a set of images, rather than a single image. For example, the set of toolbar buttons in a ToolBar object, or the images required for a set of Button controls on a form. The Windows Forms namespace provides the ImageList class for managing such collections of images. As we shall see in chapters 14 and 15, this class is also utilized by the ListView and TreeView controls. This section examines the ImageList class in some detail, and creates a set of images for use in the toolbar we created in the previous section. 13.2.1 T HE IMAGELIST CLASS The ImageList class, summarized in .NET Table 13.4, provides a convenient way to store and access images required by various objects. An ImageList component .NET Table 13.4 ImageList class The ImageList class represents a collection of Image objects. Typically, this class is used to support one or more Windows Forms controls in the management and display of images within the control. Classes that use image lists include the Button, ToolBar, ListView, and TreeView classes. This class is part of the System.Windows.Forms namespace, and inherits from the System.ComponentModel.Component class. Public Properties ColorDepth Gets or sets the color depth for images in the list. Handle Gets the Win32 handle for the image list. HandleCreated Gets whether the underlying Win32 handle has been created. Images Gets the collection of images for this image list. Use this collection to add, remove, and otherwise manage the list’s images programmatically. ImageSize Gets or sets the size for images in the list. ImageStream Gets or sets the ImageListStreamer object to associate with this list. This object manages the data associated with the list. TransparentColor Gets or sets the color to treat as transparent in the list’s images. Public Methods Draw Draws an indicated image in a specified Graphics object. Public Events RecreateHandle Occurs when the underlying Win32 handle is recreated for the list. IMAGE LISTS 417 works much like an array of Image objects, and can be thought of as such. Classes that use this construct specify an index into the list, designating which image they wish to display. Typically, a class that uses such a list provides an ImageList prop- erty to specify a list to use, and classes that display an image out of such lists provide an ImageIndex property to indicate which image to display. In Visual Studio .NET, an ImageList can be associated with a Form graphically and assigned to one or more controls within that form using the Windows Forms Designer and the Properties windows. Visual Studio creates the list within the set of components for the Form, so that it is disposed when the application disposes of the Form via the Close or Dispose methods. We will look at the code generated for this purpose in a moment. 13.2.2 C REATING AN IMAGE LIST For the ToolBar object we created in our MainForm class, we need an ImageList containing the set of images required for our ToolBarButton objects. We will use some of the bitmaps and icons in the common image directory provided with Visual Studio. If you skipped chapter 12, or were simply not paying attention, this directory is typically “C:\Program Files\Microsoft Visual Studio .NET\Common7\Graphics.” The following steps create an ImageList and associate the required image files with it. Set the version number of the MyPhotos application to 13.2. CREATE AN IMAGE LIST FOR OUR TOOLBAR Action Result 1 Associate an ImageList component with the MainForm form in the MainForm.cs [Design] window. Note: Windows Forms compo- nents such as the ImageList class are available from the Toolbox window, just like Win- dows Forms controls. The new image list is shown in the component tray area below the form. 2 Set the (Name) property for the image list to imageListToolBar. 3 Display the Image Collection Editor window. How-to Click the … button next to the Images item in the Properties window. A blank Image Collection Editor dialog box appears. This dialog with all eight images added is shown in step 5. 418 CHAPTER 13 TOOLBARS AND TIPS This creates a collection of all the images we will need for our toolbar. An excerpt of the code generated by these changes is as follows. . . . namespace MyPhotos { . . . public class MainForm : System.Windows.Forms.Form { . . . private System.ComponentModel.IContainer components = null; . . . private System.Windows.Forms.ImageList imageListToolBar; . . . protected override void Dispose( bool disposing ) { if( disposing ) { 4 Add an image for creating a new album to the collection. The image appears as member 0 within the Image Collection Editor dialog. 5 Similarly, add the following images files to the collection. 6 Click the OK button to save the changes. The assigned images are stored in the image list. CREATE AN IMAGE LIST FOR OUR TOOLBAR (continued) Action Result How-to a. Click the Add button. b. In the file dialog, locate the NEW.BMP file under the common image directory in the “bitmaps/OffCtlBr/Small/ Color” directory. c. Click the Open button to add the image. • bitmaps/OffCtlBr/Small/Color/ OPEN.BMP • bitmaps/OffCtlBr/Small/Color/ SAVE.BMP • icons/arrows/ARW08LT.ICO • icons/arrows/ARW08RT.ICO • icons/Writing/BOOK02.ICO • icons/Traffic/TRFFC10C.ICO • icons/Traffic/TRFFC10A.ICO IMAGE LISTS 419 if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } . . . private void InitializeComponent() { . . . this.imageListToolBar = new System.Windows.Forms.ImageList(this.components); . . . // // imageListToolBar // this.imageListToolBar.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageListToolBar.ImageSize = new System.Drawing.Size(16, 16); this.imageListToolBar.ImageStream = ((System.Windows.Forms.ImageListStreamer) (resources.GetObject("imageListToolBar.ImageStream"))); this.imageListToolBar.TransparentColor = System.Drawing.Color.Transparent; . . . } The annotated lines merit some additional discussion. b This line disposes of the components container, which in turn disposes of any com- ponents contained within this object. The controls on the form are contained within the Form object itself. As a result, the resources allocated to the controls in the form are disposed by the Form.Dispose method itself. This works for components such as the MainMenu and StatusBarPanel objects as well, since the menu is assigned to the form, and status bar panels are contained within status bar controls. c This line initializes an ImageList object and assigns it to the components con- tainer. This is required to ensure that the list is properly disposed of by the Form object’s Dispose method. If you create your own ImageList objects manually, be sure to dispose of the object when you are finished in order to free any Windows or file system resources assigned to the list. d Like the bitmap files we created in the previous chapter, a ResourcesManager object is used to retrieve the stream of image data from a .resources file. This data is retrieved as an ImageListStream object. This object is assigned to the Imag- eStream property and used internally by the ImageList class to manage and access the images in the collection. b Dispose of the components object Create the image list within the components container c Load the image stream for the list d 420 CHAPTER 13 TOOLBARS AND TIPS On this last point for our code, note that the MyPhotos project directory in the file system contains a MainForm.resx file that defines the binary form of the image stream for our list. This is very similar to how our bitmap images were defined for our Button objects in the previous chapter. An excerpt of this file follows. In addition to the definition of the image stream, note how the positioning of objects displayed in the component tray area of Visual Studio, such as the location of our imageList- ToolBar object, are also stored in this file <?xml version="1.0" encoding="utf-8"?> <root> . . . <data name="imageListToolBar.Location" type="System.Drawing.Point, System.Drawing, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <value>255, 17</value> </data> <data name="imageListToolBar.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64"> <value> AAEAAAD/////AQAAAAAAAAAMAgAAAFpTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0xLjAuMzMw MC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZT eXN0ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMA . . . </value> . . . </root> This completes our discussion on image lists for now. Let’s get back to the ToolBar for our application and create the ToolBarButton components using the images we just assigned to our list. 13.3 TOOLBAR BUTTONS Now that we have some understanding of image lists, we can return to the topic of toolbar buttons. This section adds the ten buttons, both images and separators, we decided to place on our toolbar. The discussion is divided into two parts. First we will look at the most basic of styles, the push button. Then we’ll tackle the dropdown and toggle styles of ToolBarButton objects. 13.3.1 A DDING A PUSH BUTTON We have a toolbar and we have an image list, so let’s get to it. We will start with the push buttons related to the File menu, and later hook up these buttons to their corre- sponding menu item, after which we will create the buttons associated with the Next and Previous menu items. TOOLBAR BUTTONS 421 Set the version number of the MyPhotos application to 13.3. Our ToolBar now contains three toolbar buttons. Visual Studio displays the images associated with each button in the designer window. If text is assigned to a button, ADD THE TOOLBAR BUTTONS FOR THE FILE MENU Action Result 1 In the MainForm.cs [Design] window, modify the properties for the toolBarMain control. The images in our image list are now available to any buttons placed on the toolbar. 2 Display the ToolBarButton Collection Editor window. How-to In the toolbar’s Properties window, click the … button associated with the Buttons item. Note: You can modify the properties for these objects in the collection editor or in the Properties window. The collection editor is shown here. To use the Properties window, create the buttons, click OK to close the window, and then simply select the desired toolbar button from the list at the top of the Properties window. 3 Click the Add button three times to create three new ToolBarButton objects. 4 Click OK to close the editor. The new buttons appear on the form. Settings Property Value ButtonSize 16, 16 ImageList imageListToolBar Settings Button Property Value 0 (New) (Name) tbbNew ImageIndex 0 ToolTipText Create album 1 (Open) (Name) tbbOpen ImageIndex 1 ToolTipText Open album 2 (Save) (Name) tbbSave ImageIndex 2 ToolTipText Save album 422 CHAPTER 13 TOOLBARS AND TIPS Visual Studio will display this as well, assuming the button provides room for the text to appear. The next step is to link these to operations within our form. The ButtonClick event in the ToolBar class is used for this purpose. Event handlers for this event receive a ToolBarButtonClickEventArgs parameter that contains a Button property. This property retrieves the ToolBarButton instance clicked by the user. One means for handling our button clicks uses a series of if statements. The code would look something like the following: private void toolBarMain_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { // Determine which button was clicked – not our approach if (e.Button == tbbNew) { menuNew.PerformClick(); } else if (e.Button == tbbOpen) { menuOpen.PerformClick(); } else if (e.Button == tbbSave) { menuSave.PerformClick(); } } This can get a bit unwieldy as the number of buttons increase. A more elegant approach takes advantage of the Tag property for ToolBarButton instances. This property holds an object instance, and in particular can hold a MenuItem object to associate with the button. Since we would like our buttons to perform the same action as the corresponding menu item, we will associate the proper menu item with each of our buttons. Continuing our prior steps: SET THE TAG PROPERTY FOR THE TOOLBAR BUTTONS Action Result 5 Create a new InitToolBarButtons method in the MainForm.cs code window. private void InitToolBarButtons() { 6 Set the Tag property for each toolbar button to the corresponding MenuItem object. tbbNew.Tag = menuNew; tbbOpen.Tag = menuOpen; tbbSave.Tag = menuSave; } 7 Add a call to this new method from the MainForm instance constructor. public MainForm() { . . . InitToolBarButtons(); } TOOLBAR BUTTONS 423 Our implementation of the ButtonClick handler for our toolbar can now take advantage of these settings to simply invoke the Click event handler associated with the corresponding menu item. Note how the as keyword is used to ensure that the Tag property does, in fact, refer to a MenuItem object. If a new button is added without an associated menu, then this code is safely ignored. We can also use this method for the Next and Previous toolbar buttons. The follow- ing steps also define a separator button to differentiate between these two sets of buttons. HANDLE THE BUTTONCLICK EVENT FOR THE TOOLBAR Action Result 8 Add a ButtonClick event handler for the ToolBar control. How-to This is the default event for toolbars, so simply double-click the toolbar control in the MainForm.cs [Design] window. private void toolBarMain_ButtonClick (object sender, System.Windows.Forms. ToolBarButtonClickEventArgs e) { 9 Implement this handler using the Tag property of the ToolBarButton component. // Handle menu buttons MenuItem mi = e.Button.Tag as MenuItem; if (mi != null) mi.PerformClick(); } ADD THE NEXT AND PREVIOUS TOOLBAR BUTTONS Action Result 10 In the ToolBarButton Collection Editor, add three new toolbar buttons. 11 Update the InitToolBarButtons method for these new buttons. private void InitToolBarButtons() { tbbNew.Tag = menuNew; tbbOpen.Tag = menuOpen; tbbSave.Tag = menuSave; tbbPrevious.Tag = menuPrevious; tbbNext.Tag = menuNext; } Settings Button Property Value 3 Style Separator 4 (Prev) (Name) tbbPrevious ImageIndex 3 ToolTipText Previous image 5 (Next) (Name) tbbNext ImageIndex 4 ToolTipText Next image 424 CHAPTER 13 TOOLBARS AND TIPS Our ButtonClick event handler automatically handles these buttons based on their associated menu items, so no further changes are needed. Compile and run the pro- gram to make use of these buttons. Note how the tool tips pop up when the mouse hovers over these buttons. TRY IT! Two things to try here. First, modify the Appearance property for the toolbar to be Flat. The buttons will no longer have a three-dimensional appearance, and the separator will be a line between the two sets of buttons. Second, modify the Dock property for the toolbar to be Left. This places the control on the left side of the form. Run the program to verify that everything still works as expected. There are two other types of toolbar buttons, namely the DropDownButton and Tog- gleButton styles. The next two sections take a look at these alternate button styles. 13.3.2 A DDING A DROPDOWN BUTTON To create a dropdown menu on our form, we will make use of our existing Images submenu displayed via the menuImages menu item created way back in chapter 3, and updated in chapter 6. The changes are detailed by the following steps, and dis- cussed in the subsequent text. ADD A DROPDOWN BUTTON Action Result 1 In the MainForm.cs [Design] window, add a new ContextMenu object to the MainForm window. A second context menu appears in the component tray. 2 Set the (Name) for the menu to ctxtMenuImage. 3 Assign the menuImage_Popup event handler as the Popup event handler for the ctxtMenuImage menu. Note: If you look at our implementation of this event handler back in chapter 3, you will find that we cast the sender parame- ter to a Menu object, rather than a Menu- Item object, so that it would work with any type of menu. 4 Modify the DefineContextMenu method to copy the contents of the menuImage menu into the new context menu. Note: This clones the submenus of the menuImage object and assigns them to the ctxtMenuImage object. We created and discussed this method in chapter 3. private void DefineContextMenu() { //Copy View menu into ctxtMenuView . . . // Copy Image menu into ctxtMenuImage foreach (MenuItem mi in menuImage.MenuItems) { ctxtMenuImage.MenuItems. Add(mi.Index, mi.CloneMenu()); } } TOOLBAR BUTTONS 425 Our new toolbar button requires a new context menu, which we use as the dropdown menu for our new button. Even though the DropDownMenu property for the Tool- BarButton class is defined as a type of Menu object, a ContextMenu instance is required to properly display a dropdown menu beneath the button. We could have used the ctxtMenuView context menu, although we would then display the entire View menu beneath the toolbar button. Compile, run, open, click, and otherwise make sure the new button works. The .NET Framework does all the hard work here. When the button is clicked, the menu item collection associated with the ctxtMenuImage menu is displayed. This causes the Popup event associated with this menu to fire, invoking the menuImage_Popup event handler. Figure 13.2 shows the application with the popup menu displayed for our new button. 5 In the ToolBarButton Collection Editor, add two new toolbar buttons. Note: The down arrow to the right of the image appears because the toolbar’s DropDownArrow property is true. Set this property to false to display the button without the arrow. ADD A DROPDOWN BUTTON (continued) Action Result Settings Button Property Value 6 Style Separator 7 (Image) (Name) tbbImage DropDownMenu ctxtMenuImage ImageIndex 5 Style DropDownButton ToolTipText Set display mode Figure 13.2 When the down arrow for a toolbar but- ton is shown, as it is here, the user must click on this arrow to display the associ- ated menu. [...]... “toolTipPhotos ” As usual, the new object is defined within the PhotoEditDlg class and initialized in the InitializeComponent method private System .Windows. Forms. ToolTip toolTipPhotos; private void InitializeComponent() { this.toolTipPhotos = new System .Windows. Forms. ToolTip(this.components); } As we saw for the ImageList in our MyPhotos application, the ToolTip is created within the Form object’s... features discussed here and in earlier chapters in this book The foundation presented so far is critical to developing and understanding Windows Forms applications, and will come in handy as we discuss the concepts presented in part 3 RECAP 435 P A R T 3 Advanced Windows Forms I f you have actually read this book from the beginning, then I applaud your fortitude and welcome you to the third and final part... document interface, or MDI, applications in Windows Forms Here we return to our MyPhotos application from part 2 and convert it into an MDI application, using our MainForm class as the child window The topic of “Data binding” is taken up in chapter 17 This discusses complex data binding by way of the DataGrid control, and simple binding of data to Windows Forms controls in general This chapter will... be of further interest These include printing, Windows Forms timers, drag and drop, and ActiveX controls An example for each topic is provided using the MyPhotos MDI application built in chapter 16 Following this last chapter are four appendices with some additional information on C#, an overview of NET namespaces, a class hierarchy chart of the Windows Forms namespace, and resources for additional... NET Framework 438 PART 3 ADVANCED WINDOWS FORMS C H A P T E R 1 4 List views 14.1 The nature of list views 440 14.2 The ListView class 443 14.3 ListView columns 453 14.4 Selection and editing 464 14.5 Item activation 472 14.6 Recap 483 To kick off the advanced section of the book, we take a detailed look at the ListView class This class is used by applications such as Windows Explorer to present a collection... Table 14.1 View enumeration The View enumeration specifies the different ways the contents of a ListView control can appear This enumeration is part of the System .Windows. Forms namespace The following table provides an example obtained from the Windows Explorer application LargeIcon Enumeration Values SmallIcon 440 Each item appears as a large icon with a label below it By default, items can be dragged... window normally contains a short phrase describing the purpose of the control, and appears whenever the mouse hovers over the control for a configurable amount of time This class is part of the System .Windows. Forms namespace, and supports the IExtenderProvider interface The ToolTip class derives from the System.ComponentModel.Component class Active AutomaticDelay InitialDelay Gets or sets the time in milliseconds... small icons, in a list format, or in a detailed list format The detailed list permits additional information about each item to appear in columns within the control This class is part of the System .Windows. Forms namespace, and inherits from the Control class See NET Table 4.1 on page 104 for a list of members inherited by this class Activation Gets or sets how an item is activated, and whether the font... ListViewItem for each album 448 CHA PTE R 14 LIST VIEWS .NET Table 14.3 ListViewItem class The ListViewItem class is an object that can be displayed within a ListView control It is part of the System .Windows. Forms namespace, and supports the IClonable and ISerializable interfaces ListViewItem Initializes a new ListViewItem instance Overloads ListViewItem(string label); ListViewItem(string[] labelAndSubitems);... EACH ALBUM TO THE VIEW Action 5 In the MainForm.cs source code window, indicate that this file will use members of the System.IO and the Manning. MyPhotoAlbum namespaces 6 Add a set of constant fields for the image list indices required Result using System.IO; using Manning. MyPhotoAlbum; private const int PhotoIndex = 0; private const int AlbumIndex = 1; private const int ErrorIndex = 2; Note Using constants . . . public class MainForm : System .Windows. Forms. Form { . . . private System.ComponentModel.IContainer components = null; . . . private System .Windows. Forms. ImageList imageListToolBar; . this.imageListToolBar = new System .Windows. Forms. ImageList(this.components); . . . // // imageListToolBar // this.imageListToolBar.ColorDepth = System .Windows. Forms. ColorDepth.Depth8Bit; . InitializeComponent method. private System .Windows. Forms. ToolTip toolTipPhotos; . . . private void InitializeComponent() { . . . this.toolTipPhotos = new System .Windows. Forms. ToolTip(this.components);

Ngày đăng: 07/07/2014, 04:20

TỪ KHÓA LIÊN QUAN