Search code examples
c#winformsmousetoolstrip

Mouse button in ToolStripMenuItem


I have a context menu with a few items. One of the items has a submenu (or whatever it's called) with a few items (depends on what files it finds).

What I want to do is when I left click one of the sub-items I want one thing to happen, and when I right click I want another thing to happen.

My problem is that when I use the filesToolStripMenuItem_DropDownItemClicked, I don't get any MouseEventArgs in the parameter, so I can't find out which mouse button was used to click the item.

I tried adding it myself in the parameter but I get some error then.

Does anyone know how I can fix this? So I can find out what mouse button was used to click the sub-item (which is a ToolStripMenuItem)?

Thanks

edit: here is the code I use to create the sub items:

IPHostEntry ipE = Dns.GetHostEntry(Dns.GetHostName());
IPAddress[] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
      if (!IpA[i].ToString().Contains(":"))
           cxItems.Items.Add(new ToolStripMenuItem(IpA[i].ToString()));
}

And for those items I want to be able to do different things depending on which mouse button I use


Solution

  •  private void button2_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item1 = new ToolStripMenuItem("Menu1");
            ToolStripMenuItem subMenuitem1 = new ToolStripMenuItem("SubMenu");
            item1.DropDownItems.Add(subMenuitem1);
            this.contextMenuStrip1.Items.Add(item1);
            subMenuitem1.MouseDown += new MouseEventHandler(subMenuitem1_MouseDown);
            this.contextMenuStrip1.Show(this.button2,new Point(0,0));
        }
    
        void subMenuitem1_MouseDown(object sender, MouseEventArgs e)
        {
            //e.Button will determine which button was clicked.
            MessageBox.Show(e.Button.ToString());
        }
    

    That should help get you started.

    RE: You're edit:

    The problem is, you're just saying new ToolStripMenuItem(IpA[i].ToString()) without keep a reference to it. Here's how you need to do it:

     IPHostEntry ipE = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress[] IpA = ipE.AddressList;
        for (int i = 0; i < IpA.Length; i++)
        {
              if (!IpA[i].ToString().Contains(":"))
              {
                   ToolStripMenuItem subItem = new ToolStripMenuItem(IpA[i].ToString());
                   subItem.MouseDown += new MouseEventHandler(subItem_MouseDown);
                   cxItems.Items.Add(subItem);
              }
        }
    
        void subMenuitem1_MouseDown(object sender, MouseEventArgs e)
        {
              //get a reference to the menu that was clicked
              ToolStripMenuItem clickedMenu = sender as ToolStripMenuItem;
              //e.Button will tell you which button was clicked.
        }