Netframwork 2.0 (phần 5) doc

50 374 0
Netframwork 2.0 (phần 5) doc

Đ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

Lesson 2: Creating and Configuring Menus 175 Copying Menu Items from Existing Menu Strips at Run Time You will frequently want to create context menus that also expose the same menu items as items in regular menus. Although a single tool strip menu item can belong to only one menu strip at a time, it is a simple task to create an exact copy of a menu item at run time. The ToolStripMenuItem constructor has several overloads that allow you to specify the text, image, and click event handler. The following example demon- strates how to make a copy of an existing tool strip menu item named ExitToolStrip- MenuItem and add it to a ContextMenuStrip control named ContextMenuStrip1. This example assumes the existence of a method named ExitToolStripMenuItem_Click, which is the event handler for the ExitToolStripMenuItem.Click event. ' VB Dim anItem As ToolStripMenuItem anItem = New ToolStripMenuItem(ExitToolStripMenuItem.Text, _ ExitToolStripMenuItem.Image, New EventHandler(addressof _ ExitToolStripMenuItem_Click)) ContextMenuStrip1.Items.Add(anItem) // C# ToolStripMenuItem anItem; anItem = new ToolStripMenuItem(ExitToolStripMenuItem.Text, _ ExitToolStripMenuItem.Image, new EventHandler(ExitToolStripMenuItem_Click)); ContextMenuStrip1.Items.Add(anItem); Quick Check 1. What is the difference between a MenuStrip and a ContextMenuStrip? 2. How do you associate a ContextMenuStrip with a control? Quick Check Answers 1. A ContextMenuStrip is designed to be shown when the user right-clicks on a control. Thus it contains no top-level elements and has no visual presence on the form until a control is right-clicked. 2. You can associate a ContextMenuStrip with a control by setting that con- trol’s ContextMenuStrip property. 176 Chapter 4 Tool Strips, Menus, and Events Lab 2: Adding File Browsing Capability to Your Web Browser In this lab, you will extend the capabilities of the Web browser you created in Lesson 1, “Configuring Tool Strips.” You will add a menu, with menu items that allow you to browse, print, or save a file. � Exercise 1: Extending the Capabilities of Your Web Browser 1. Open your completed lab from Lesson 1 or load the Lab 1 solution from the folder on the companion CD. 2. Open Form1. In the Designer, drag a MenuStrip control from the Toolbox to the top panel of the ToolStripContainer. 3. Add a top-level tool strip menu item named &File to the menu strip. 4. Add the following sub-menu items to the File tool strip menu item: &Open, &Print, P&rint Preview, &Save, and &Exit. 5. From the Toolbox, drag an OpenFileDialog component onto the form. 6. In the Designer, double-click OpenToolStripMenuItem to open the code window to the OpenToolStripMenuItem_Click event handler. Add the following code to this method: ' VB Dim result As DialogResult result = OpenFileDialog1.ShowDialog() If result = System.Windows.Forms.DialogResult.OK Then WebBrowser1.Navigate(OpenFileDialog1.FileName) End If // C# DialogResult result; result = openFileDialog1.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) webBrowser1.Navigate(openFileDialog1.FileName); 7. Double-click the PrintToolStripMenuItem to open its Click event handler and add the following code: ' VB WebBrowser1.ShowPrintDialog() // C# webBrowser1.ShowPrintDialog(); 8. Double-click the PrintPreviewToolStripMenuItem and add the following line to its Click event handler: ' VB WebBrowser1.ShowPrintPreviewDialog() Lesson 2: Creating and Configuring Menus 177 // C# webBrowser1.ShowPrintPreviewDialog(); 9. Double-click the SaveToolStripMenuItem and add the following line to its Click event handler: ' VB WebBrowser1.ShowSaveAsDialog() // C# webBrowser1.ShowSaveAsDialog(); 10. Double-click the ExitToolStripMenuItem and add the following line to its Click event handler: ' VB Application.Exit() // C# Application.Exit(); 11. In the Properties window, set the ShortCutKeys property of ExitToolStripMenu- Item to Ctrl+E. 12. Press F5 to test your application. Lesson Summary ■ The MenuStrip control is the host for ToolStripMenuItems, which represent indi- vidual menu items. The top-level menu items in a menu strip are contained in the Items collection. ■ Individual tool strip menu items can host their own sub-menus, which are con- tained in the DropDownItems collection. ■ Individual menu items can be displayed with check marks next to the menu items and can have access keys and shortcut keys to allow keyboard-based navigation. ■ Menus can be merged by using the ToolStripManager.Merge method. The config- uration of the menu resulting from a merge is determined by the individual Tool- StripMenuItem MergeAction and MergeIndex properties. ■ ContextMenuStrip allows you to create context menus for your application. Menus created with the ContextMenuStrip control are not visible at run time and do not host a top-level menu but behave like MenuStrip controls otherwise. You can associate a ContextMenuStrip with a control by setting the control’s Context- MenuStrip property. 178 Chapter 4 Tool Strips, Menus, and Events Lesson Review You can use the following questions to test your knowledge of the information in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each choice is right or wrong are located in the “Answers” section at the end of the book. 1. Which of the following are required to create an access key for a menu item? A. The UseMnemonic property for the ToolStripMenuItem must be set to True. B. The AccessKeys property must be set to the correct key. C. The letter for the access key in the Text property must be preceded by an ampersand (&) symbol. D. The ShortCutKeys property must be set to Ctrl + the letter for the access key. 2. Which of the following code snippets will add a new menu named Menu1 to a form at run time? A. ' VB ToolStripManager.Menus.Add(Menu1) // C# ToolStripManager.Menus.Add(Menu1); B. ' VB ToolStripManager.Merge(Form1, Menu1) // C# ToolStripManager.Merge(Form1, Menu1); C. ' VB ToolStripManager.Controls.Add(Menu1) // C# ToolStripManager.Controls.Add(Menu1); D. ' VB Me.Controls.Add(Menu1) // C# this.Controls.Add(Menu1); Lesson 2: Creating and Configuring Menus 179 3. Which of the following are required to associate and enable a context menu strip named ContextMenu1 with a button named Button1? A. The ContextMenuStrip property for Button1 must be set to ContextMenu1. B. The ShowPopUp property for Button1 must be set to True. C. Button1 must call the ContextMenu1.ShowPopUp method in its RightClick event handler. D. The ContextMenu1.Control property must be set to Button1. 180 Chapter 4 Tool Strips, Menus, and Events Lesson 3: Using Events and Event Handlers Events are messages that represent something interesting happening in your applica- tion. When an event is raised, other parts of your application are given an opportunity to respond to those events by executing methods called event handlers. In this lesson, you will learn how to work with form and control events, how to assign event han- dlers at design time, and how to assign event handlers at run time. You will also learn how to use the code editor to override methods that are defined in your base class. After this lesson, you will be able to: ■ Use the Windows Forms Designer to create default event handlers. ■ Use the Windows Forms Designer to create event handlers. ■ Manage mouse and keyboard events within Windows Forms applications. ■ Program a Windows Forms application to recognize modifier keys. ■ Create event handlers at run time to respond to system or user events dynamically. ■ Connect multiple events to a single event handler. ■ Use the Code Editor to override methods defined in the base class. Estimated lesson time: 30 minutes Overview of Events Events are members of the class or control that raises them. You’ve been using events throughout the labs in this book. Whenever you create an OnClick method, you are responding to that control’s Click event. An event represents a message that is sent to the rest of the application. When something noteworthy happens, a control or class can raise an event, which sends out the message. This message can wrap any argu- ments that contain information about the event and send them out to the rest of the application. A method that has the same signature as the event (i.e., it has the same number and types of parameters) can handle the event, which means that the method is executed when the event occurs. An event can be handled by more than one method, and a given method can handle more than one event. Controls and forms can raise a variety of events in response to user input. The most familiar event is the Click event, which is raised by almost all controls when the mouse is positioned on the control and the left mouse button is clicked. Other common events exposed by controls include events that respond to mouse and keyboard Lesson 3: Using Events and Event Handlers 181 input. Some common events raised by controls are shown in Table 4-8. Table 4-8 Common Events Raised by Controls Event Description Click Occurs when the left mouse button is clicked. Depending on the control, it can also occur with certain keyboard input, for example, when the control is selected and the Enter key is pressed. DoubleClick Occurs when the left mouse button is clicked twice rapidly. Not all controls respond to the DoubleClick event. KeyDown Occurs when a key is pressed when a control has the focus. Contains different information from the KeyPress event. KeyPress Occurs when a key is pressed when a control has the focus. Contains different information from the KeyDown event. KeyUp Occurs when a key is released while the control has the focus. MouseClick Occurs when a control is clicked by the mouse. MouseDoubleClick Occurs when a control is double-clicked by the mouse. MouseDown Occurs when the mouse pointer is over a control and the mouse button is pressed. MouseEnter Occurs when the mouse pointer enters the control. MouseHover Occurs when the mouse pointer rests on the control. MouseLeave Occurs when the mouse pointer exits the control. MouseMove Occurs when the mouse moves over the control. MouseUp Occurs when a mouse button is released over the control. MouseWheel Occurs when the mouse wheel moves while the control has the focus. Each event carries some information about itself to the method that handles it. Events raised by controls usually contain two parameters: a parameter that carries an object ref- erence to the control that raised it and a parameter that derives from the EventArgs class 182 Chapter 4 Tool Strips, Menus, and Events that carries event arguments. In some events, such as the Click event, the EventArgs argu- ment carries practically no information. In others, such as the MouseClick event, a great deal of information about the state of the mouse is carried in the MouseClickEventArgs argument. Creating Event Handlers in the Designer You can create event handlers in the Designer by using the Properties window. By pressing the “lightning bolt” button in the Properties window (shown in Figure 4-6), Figure 4-6 The Events button in the Properties window The Properties window displays the events that can be raised by the control, as shown in Figure 4-7. Figure 4-7 The Properties window configured to display events Creating Default Event Handlers You can create default event handlers for an event through the Properties window. A default event handler is a method that handles a given event for a control and has a descriptive name. For example, the default event handler for the Click event of a but- ton named Button1 would be called Button1_Click. The following procedure describes how to create a default event handler. Lesson 3: Using Events and Event Handlers 183 � To create a default event handler 1. In the Designer, select the control. In the Properties window, click the “lightning bolt” button to list events for that control. 2. Double-click the entry for the event for which you want to create the default event handler. The method is created with the proper signature and the Code Editor opens to the new method. 3. Add the code that you want to execute when the event is raised. Creating Event Handlers in the Designer In addition to default event handlers, you can use the designer to assign other meth- ods to handle events raised by controls. The following procedure describes how to create an event handler other than the default event handler. 1. In the Code Editor, create a method whose signature matches the signature of the event that you want to handle. For example, if you wanted to handle the But- ton.Click event, you would create a Sub (void) method with Object and EventArgs parameters. 2. In the Designer, select the control for which you want to create an event handler. In the Properties window, click the lightning bolt to list the events for this control. 3. Single-click the cell next to the event you want to create a handler for. A drop- down arrow appears. 4. Click the drop-down arrow to display a list of methods that match the signature of the event. Choose the event you created in the Code Editor. Assigning Multiple Events to the Same Event Handler You can assign multiple events to the same event handler. All that is required is that the signature of the method matches the signature of the event. You can assign mul- tiple events in a single control to a single event handler, or you can assign events from several controls to a single event handler. An example of when this might be useful would be in an application such as a calculator. You might have the Button controls that are used to input numbers all share the same Click event handler, programming logic into the event handler to distinguish between the buttons that are clicked. You can assign multiple events to the same event handler in the same way that you assign an individual event. Select the control and then, in the Properties window, select the event for which you want to assign a handler. Choose the method for the 184 Chapter 4 Tool Strips, Menus, and Events event handler from the drop-down menu. Repeat the process for each event you want to assign a handler to. Managing Mouse and Keyboard Events Most of the events involved in interacting with the user are mouse and keyboard events. Controls can raise events in response to mouse clicks or a variety of keystrokes and can detect whether modifier keys such as Ctrl, Alt, or Shift are pressed. This sec- tion describes how to respond to mouse and keyboard events. Mouse Events Controls can interact with the mouse in several ways. Controls raise events when the mouse enters the control, leaves the control, moves over the control, clicks, hovers over the control, or when the mouse wheel moves while the pointer is over a control. Click and DoubleClick The most familiar mouse events are the Click and DoubleClick events. The Click event is raised by a control when the mouse pointer is over the con- trol and the left button is pressed and released. This event is also raised when the con- trol has the focus and the Enter key is pressed. The DoubleClick event is raised when the left mouse button is clicked twice in rapid succession. Note that not all controls respond to the DoubleClick event. The Click and DoubleClick events have a fairly simple signature. They return an Object reference to the control that raised the event (the parameter that Visual Studio names Sender when it generates a handler) and an instance of the EventArgs class that carries no useful information about the event. The following code example demonstrates the appropriate signature for an event handler that handles the Click or DoubleClick event. ' VB Private Sub ClickHandler(ByVal sender As System. Object, ByVal e As _ System.EventArgs) ' Insert code to be executed when the event is raised End Sub // C# private void ClickHander(object sender, EventArgs e) { // Insert code to be executed when the event is raised } You can assign any method with this signature to handle the Click or DoubleClick events. . right-clicked. 2. You can associate a ContextMenuStrip with a control by setting that con- trol’s ContextMenuStrip property. 176 Chapter 4 Tool Strips, Menus, and Events Lab 2: Adding File. pass an instance of MouseEventArgs in its signature. These events are shown in table 4- 10. Table 4- 10 Mouse Events That Pass MouseEventArgs Event Description MouseClick This event is raised. Events Table 4- 10 Mouse Events That Pass MouseEventArgs Event Description MouseWheel This event is raised when the mouse wheel is moved. All of the events shown in Table 4- 10 require a handler

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

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan