
help working with context menus and adding menu items dynamically
Hello Dave,
You may create a ContextMenu and add the Event Handler to the click event.
There is a sample code demonstrates show a context menu on the nodes of a
Treeview control:
private void treeView1_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
// logic to show context menu
if(e.Button == MouseButtons.Right)
{
Point ClickPoint = new Point(e.X,e.Y);
TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
if(CurrentNode == null)
return;
// Convert from Tree coordinates to Screen
Point ScreenPoint = treeView1.PointToScreen(ClickPoint);
// Convert from Screen to Form
Point FormPoint = this.PointToClient(ScreenPoint);
// showing the context menu
// in Add use an overloaded that adds an eventhandler or anything else
ContextMenu menu = new ContextMenu();
menu.MenuItems.Clear();
menu.MenuItems.Add("Option 1");
menu.MenuItems[0].Click += new EventHandler(Option1_Click);
menu.MenuItems.Add("Option 2");
menu.MenuItems[1].Click += new EventHandler(Option2_Click);
menu.Show(this,FormPoint);
}
Quote:
}
private void Option1_Click(object sender, EventArgs e)
{
MessageBox.Show("Option1_Click");
Quote:
}
private void Option2_Click(object sender, EventArgs e)
{
MessageBox.Show("Option2_Click");
Quote:
}
I hope this helps.
Best regards,
Lion Shi, MCSE, MCSD
Microsoft Support Engineer
This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use. 2001 Microsoft Corporation. All rights
reserved.
--------------------
Subject: help working with context menus and adding menu items
dynamically
Date: Mon, 8 Jul 2002 15:35:15 -0400
Lines: 18
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2600.0000
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000
Newsgroups: microsoft.public.dotnet.languages.CSharp
NNTP-Posting-Host: 63.121.77.30
Path: cpmsftngxa07!tkmsftngp01!tkmsftngp11
Xref: cpmsftngxa07 microsoft.public.dotnet.languages.csharp:74004
X-Tomcat-NG: microsoft.public.dotnet.languages.csharp
I have a need to add menu items to a context menu dynamically,
depending on
the area clicked. So for instance, when you right click, I pop up a
context
menu. The menu items in the context menu need to be added dynamically
depending on which control I clicked on. So there could be 1 menu
item, 2,
3, 4, etc. My question is ... how do I add the menu item's dynamically
and
assign their click events to a method? I know how to add the menu
items to
the context menu and I know that if I were to create a class level menu
item
I could assign it's click event in the initialize of the form. But in
thi
instance, I do not know how many menu items will be needed so I want to
create them at the time the right-click of the mouse occurs. So how do
I
assign their click events?
I'm sure there is a very simple answer to this, but I have not been
able to
find any examples yet. Help would be appreciated.
Dave