Previous Page
Next Page

Pop-Up Menus

Many Windows applications make use of pop-up menus that appear when you right-click a form or control. These menus are usually context-sensitive and display commands that are applicable only to the control or form that currently has the focus. They are sometimes referred to as context menus.

Creating Pop-Up Menus

In the following exercises, you will create two pop-up menus. The first pop-up menu is attached to the firstName and lastName text box controls and allows the user to clear these controls. The second pop-up menu is attached to the form and contains commands for saving the currently displayed member's information and for clearing the form. To do this, you will make a copy of an existing menu item as well as create a new one.

Create the firstName and lastName pop-up menus
  1. In the Design View window displaying MemberForm, drag a ContextMenuStrip control from the Menus & Toolbars category in the Toolbox and drop it on the form.

    A ContextMenuStrip object called contextMenuStrip1 appears at the bottom of the form and another menu strip appears at the top of the form. Note that this is only a temporary location for this new menu strip; it is just placed there by Visual Studio 2005 to allow you to edit it and add menu items. At runtime its location will actually be determined by the position of the mouse when the user clicks the right mouse button.

    Graphic
  2. Select the contextMenuStrip1 control, type textBoxMenu in the (Name) text box in the Properties window, and then press Enter.

  3. Click the Type Here caption that appears under the ContextMenuStrip menu strip at the top of the form (not the control). Type Clear Text, and then press Enter

    TIP
    If the ContextMenuStrip menu strip has disappeared from the form, click the textBoxMenu control underneath the form to display it again.
  4. Click the firstName text box control (next to the First Name label). In the Properties window, change the ContextMenuStrip property to textBoxMenu. The ContextMenu property determines which menu (if any) will be displayed when the user right-clicks the control.

  5. Click the lastName text box control. In the Properties window, change the ContextMenuStrip property to textBoxMenu.

    Notice that multiple controls are allowed to share the same context menu.

  6. Click the textBoxMenu context menu control. Click the Events button, type textBoxContextMenuPopup in the Opening event text box, and then press Enter.

    A new event method called textBoxContextMenuPopup is created and displayed in the Code And Text Editor. This event is raised whenever the context menu appears.

  7. Add the following statements to the textBoxContextMenuPopup event method:

    this.Tag = ((ContextMenuStrip)sender).SourceControl;

    The sender parameter to this event method will be the textBoxMenu object. This object contains a useful property called SourceControl that references the control the user is visiting when invoking the context menu. This statement stores a reference to the current text box control in the Tag property of the form.

    The Tag property of a form is a general-purpose item that can be use to hold any useful piece of data.

  8. Return to the Design View window. Click the textBoxMenu control at the bottom of the form to display the ContextMenuStrip again. Click the Clear Text item.

  9. In the Properties window, click the Events button, type textBoxClearClick in the Click event text box, and then press Enter.

    A new event method called textBoxClearClick is created and displayed in the Code And Text Editor.

  10. Add the following statements to the textBoxClearClick event method:

    if (this.Tag.Equals(firstName))
    {
        firstName.Clear();
        firstName.Focus();
    }
    else
    {
        lastName.Clear();
        lastName.Focus();
    }

    The if statement determines which of the two text boxes was clicked and clears it. The Focus method for a control places the cursor in that control; right-clicking a control does not automatically give it the focus.

    TIP
    This use of the Opening event to cache a reference to the current text box control in the Tag property property of a form is a workaround for a minor bug in Visual Studio 2005. A context menu item also has a SourceControl property that identifies which control the user was in when invoking the menu item. However, in Beta 2 of Visual Studio 2005, this property currently returns the value null.
  11. On the Debug menu, click Start Without Debugging.

    The project compiles and runs.

  12. When the form appears, click File and then click New. Type a name into the First Name and Last Name text boxes.

  13. Right-click the First Name text box.

    The pop-up menu appears containing only the Clear Text command.

  14. Click the Clear Text command.

    The First Name text box is cleared.

  15. Type a name into the First Name text box, and then move to the Last Name text box. Right-click the Last Name text box to display the pop-up menu. Click the Clear Text command.

    This time, the Last Name text box is cleared (the first name information should still be there).

  16. Right-click anywhere on the form.

    Because only the First Name and Last Name text boxes have pop-up menus, no pop-up menu appears.

  17. Close the form.

Before tackling the second pop-up menu, you need to add some functionality to the Save Member menu item. Currently, it doesn't do anything. When it is clicked, the data on the form should be saved to a file. For the time being, you will save the information to an ordinary text file called Members.txt in the current folder. Later, you will modify the code to allow the user to select an alternative filename and location.

Write the saveMemberClick event method
  1. Display MemberForm in the Design View window. Click the File menu, and then click Save Member.

  2. In the Properties window, click the Events button. Select the Click event, type saveMemberClick, and then press Enter.

  3. In the Code And Text Editor window, scroll to the top of the MemberForm.cs file and add the following using statement to the list:

    using System.IO;
  4. Return to the saveMemberClick event method at the end of the MemberForm.cs file. Add the following statements to the body of the method:

    StreamWriter writer = new StreamWriter("Members.txt");
    writer.WriteLine("First Name: " + firstName.Text);
    writer.WriteLine("Last Name: " + lastName.Text);
    writer.WriteLine("Tower: " + towerNames.Text);
    writer.WriteLine("Captain: " + isCaptain.Checked);
    writer.WriteLine("Member Since: " + memberSince.Text);
    writer.WriteLine("Methods: ");
    foreach(object methodChecked in methods.CheckedItems) {
        writer.WriteLine(methodChecked.ToString());
    }
    writer.Close();
    
    MessageBox.Show("Member details saved", "Saved");

    This block of code creates a StreamWriter object that is used for writing text to the Member.txt file. Using the StreamWriter class is very similar to displaying text in a console application by using the Console object—you can simply use the WriteLine method.

    The most complex part of this code is the foreach statement that iterates through the methods control. The CheckedListBox class provides a property called CheckedItems that contains all of the items that have been checked. The foreach statement sends each checked item to the StreamWriter for output.

    TIP
    When the user runs the form, they currently have to click each method in the CheckedListBox twice; once to select the method, and the second time to check it. The CheckedListBox control has another property called CheckOnClick. When you set this property to true, clicking a row in the CheckedListBox control selects and checks it with a single click.

    When the details have all been written out, the StreamWriter is closed and a message box is displayed giving the user some feedback (always a good idea).

  5. On the Debug menu, click Start Without Debugging to build and run the application.

  6. Add a new member and type some details. Click File, and then click Save Member. After a short delay, you will see the message “Member details saved”. Click OK, and then close the form.

  7. Using Windows Explorer, navigate to the \Microsoft Press\Visual CSharp Step by Step\Chapter 21\BellRingers\bin\Debug folder in your My Documents folder.

    You will see a file called Members.txt in this folder.

  8. Double-click Members.txt to display its contents using Notepad. You should see the details of the new member.

  9. Close Notepad, and return to Visual Studio 2005.

Now you can add the second pop-up menu.

To provide a bit of variation, and to show you how easy it is to create pop-up menus, in the following exercise you will create the MemberForm pop-up menu by using code. The best place to put this code is in the constructor of the form.

Create the MemberForm context menu
  1. Switch to the Code View for MemberForm. (On the View menu, click Code.)

  2. Locate the constructor for MemberForm. This is actually the first method in the class and is called MemberForm.

    A menu contains an array of menu items. In this example, the pop-up menu for the form will contain two menu items (Save Member and Clear).

  3. In the constructor, after the call to the Reset method, add the following statement:

    ToolStripMenuItem[] formMenuItemList = new ToolStripMenuItem[2];

    This line of code creates an array big enough to hold two menu items.

  4. The first item on the menu is a copy of the existing saveMemberToolStripItem menu item you created earlier. Add it to the formMenuItemList array:

    formMenuItemList[0] = new ToolStripMenuItem("Save Member", null, 
        new System.EventHandler(saveMemberClick));

    The constructor specifies the text that appears for the menu item, an image to use (null in this case), and a delegate referring to the event method to be called when the Click event occurs. This is the same method that you created in the previous exercise.

    You might be tempted simply to reference the existing saveMemberToolStripItem object created earlier rather than creating another, identical menu item. You should avoid doing so for two reasons. First, you might want to change the properties of this instance of the item without affecting the main menu of the form. Second, if you don't copy the Save Member menu item, it disappears from the form's main menu when you reference it in the context menu. (Try it and you will see!)

  5. You can create the second item (Clear) in the same way. In Chapter 20, you created a button (also called Clear) that did the same thing. You can take the event method of that button and recycle it for this menu item. Add the following statements:

    formMenuItemList[1] = new ToolStripMenuItem("Clear", null 
        new System.EventHandler(clearClick));
  6. Add the following statements:

    ContextMenuStrip formMenu = new ContextMenuStrip();
    formMenu.Items.AddRange(formMenuItemList);

    This code creates a new ContextMenuStrip and adds the array containing the Save Member and Clear menu items.

  7. Associate the pop-up menu with the form by adding the following statements:

    this.ContextMenuStrip = formMenu;
    this.ContextMenuStrip.Enabled = false;

    The context menu should be disabled initially as the user cannot input any member data until she clicks New on the File menu.

  8. Locate the newClick method. Add the following statement that enables the formMenu to the end of the method:

    this.ContextMenuStrip.Enabled = true;
  9. Compile and run the project. Create a new member and input some values. If you right-click anywhere on the form (apart from the First Name and Last Name text boxes), the pop-up menu appears. If you click Clear, the form resets back to its default values. If you click Save Member, the details you have entered are saved to the file Members.txt.

  10. Close the form when you have finished.


Previous Page
Next Page