RBU Lesson 23 Contextual Menus updated

<< Lesson 16 << /\ Back to REALbasic /\

By Peter F. Whyte, 5 Feb 2009

Original article: REALbasic University Lesson 23: Adding a Contextual Menu (8 Aug 2001)

Indented sections are taken from the original article.

Another great interface tool of modern computing is the ContextualMenu. These are hidden menus that popup when a user clicks the mouse while holding down the Control key. Ideally they live up to their name and are actually contextual: that is, they change depending on the user’s current situation.

The whole process of adding a ContextualMenu has changed since the original tutorial. Each window and each control have two actions: ConstructContextualMenu and ContextualMenuAction.

We’ll construct a short ContextualMenu with two sections: Import and Export, then Copy, Cut, and Paste. (See at end for screenshot.)

Double-click on Window1 to go into the code editor. Select the ConstructContextualMenu action and enter the following code:

Source code for Window1.ConstructContextualMenu:

  base.Append(new MenuItem("Import"))
  base.Append(new MenuItem("Export"))
  base.Append(new MenuItem(MenuItem.TextSeparator))
  base.Append(new MenuItem("Copy"))
  base.Append(new MenuItem("Cut"))
  base.Append(new MenuItem("Paste"))

  Return true // display menu


Each menu item is added to the base parameter of the action function with base.Append. That requires a MenuItem object which takes a string parameter which represents the text displayed on the menu item. The MenuItem.TextSeparator adds a line between sections of a menu.

Once the menu items have been added the function needs to return the value true so that the menu will be displayed.

Select the ContextualMenuAction action and enter the following code:

Source code for Window1.ContextualMenuAction:

  select case hitItem.Text
  case "Import"
    MsgBox "You chose import"
  case "Export"
    MsgBox "You chose export"
  case "Copy"
    MsgBox "You chose copy"
  case "Cut"
    MsgBox "You chose cut"
  case "Paste"
    MsgBox "You chose paste"
  end select

  Return true


In the example we have simply displayed message boxes for each item chosen from the menu, but, of course, any actions desired would be added to each case statement.

The finished program looks like this when it runs:

Contextual Menu in REALbasic program

Contextual Menu in REALbasic program


<< Lesson 16 << /\ Back to REALbasic /\

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.