• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 732
  • Last Modified:

C# WinForms: Alternating between ContextMenuStrips

I have defined three ContextMenuStrips, one for each of three node types.  But I use all three node types in each of three TreeViews.  So I think I need to programatically switch the ContextMenuStrip upon a right mouse click, then allow the context menu to open normally.

Am I seeing this right?

If so, I would need to:

1. Create my own class which inherits from TreeView
2. Override this event:
        protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)
3. Find if it's a right mouse click?? (how do I do this since the event I am given is TreeNodeMouseClickEventArgs)
4. Set the ContextMenuStrip property of the TreeView
5. What next?

I am pretty sure if I did this, the context menu would not open.

Can I open it manually?
3 Solutions
käµfm³d 👽Commented:
how do I do this since the event I am given is TreeNodeMouseClickEventArgs
TreeNodeMouseClickEventArgs has a Button property which you can inspect to see which button was clicked.


if (e.Button == MouseButtons.Right)
    // do something

Open in new window

I think button click might be too late in the event sequence to change the CM. You might try MouseDown--even then, I'm not sure if you'll beat the CM showing.
Luis PérezSoftware Architect in .NetCommented:
The context menu will open right. But you don't even need to override the OnNodeMouseClick event, you only need to control the TreeView's NodeMouseClick event. Anyway, it's on your own, it will work right in both scenarios.

To manually open a ContextMenuStrip, you can do the following:

Open in new window

Hope that helps.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Agreed.  I'd skip #4 entirely:

    4. Set the ContextMenuStrip property of the TreeView

Leave the ContextMenuStrip property unassigned, and then display the ContextMenuStrip of your choosing as Roland describes based on the node type that was clicked.
newbiewebAuthor Commented:

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now