galford13x
galford13x

Reputation: 2531

dynamic context menus

I'm trying to come up with a solution to create dynamic context menus that can be generated at run time. I have implemented a IGuiCommand interface that implements something similar to the normal Command pattern.

interface IGuiCommand
{
    Execute();
    Undo();
    bool CanUndo {get;set;}
    Redo();
    string CommandName {get;set;}
    string CommandDescription {get;set;}
}

The idea is to allow the control that is Right Clicked to submit it's own list of commands to display in a given context menu.

While I could have each control build a context menu, I would prefer to use a single context menu and dynamicly generate the menu to allow easier management during run time. When a control state or application state changes, I would like the context menu to reflect the change. For example if I right click a checkbox, then the checkbox would submit to the context menu an Enable or Disable command to display depending on the checkbox's current Checked value.

I think I could easily implement this if I had some way to know which control was "Right Clicked" in order to bring up the context menu for that specific control.

It seems surprising the ContextMenu events doesn't supply an EventArg that indicates the control that was right clicked (or whatever command that would cause the context menu to Popup)

Upvotes: 3

Views: 2829

Answers (1)

Randall Borck
Randall Borck

Reputation: 854

You just need to override the ContextMenuStrip_Opening event. The sender object is a ContextMenuStrip, which contains a SourceControl element. When you apply the proper cast, you will have access to everything you need.

private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
  var contextMenu = (sender as ContextMenuStrip);
  if (contextMenu != null) {
    var sourceControl = contextMenu.SourceControl;
    contextMenuStrip1.Items.Clear();
    //contextMenuStrip1.Items.Add(...);
  }
}

Upvotes: 2

Related Questions