Search code examples
c#.netwinformsnotifyiconcontextmenustrip

Event handler for a ContextMenuStrip of NotifyIcon in C#


I want to write a click event for a ContextMenuStrip. I have linked this context menu strip to a NotifyIcon.

How can I do that? This is the code I have used:

ContextMenuStrip checkers_contact_menu = new ContextMenuStrip();
checkers_contact_menu.Items.Add("Open Mailbox");
checkers_contact_menu.Items.Add("About");
alert_sender.ContextMenuStrip = checkers_contact_menu;

I tried this

ContextMenuStrip checkers_contact_menu = new ContextMenuStrip();
checkers_contact_menu.Items.Add("Open Mailbox",null,openMailBoxToolStripMenuItem_Click);

private void openMailBoxToolStripMenuItem_Click(object sender, ToolStripItemClickedEventArgs e)
{
  MessageBox.Show("Mail box");
}

But I am getting an error saying that

Error 1 The best overloaded method match for 'System.Windows.Forms.ToolStripItemCollection.Add(string, System.Drawing.Image, System.EventHandler)' has some invalid arguments

PS: the code is working , I had the event handler as ToolStripItemClickedEventArgs e which should have been EventArgs e. Now the code works fine. Thanks for your help :)


Solution

  • You need to stub out the event handler method:

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e) {
       MessageBox.Show("About");
    }
    

    And then when you add your menu item, you specify the event handler method as one of its parameters:

    checkers_contact_menu.Items.Add("About", null, aboutToolStripMenuItem_Click);