How to add ContextMenu to the system tray icon programmatically?

user2622971 picture user2622971 · Jul 30, 2013 · Viewed 32.8k times · Source

I want to programmatically add a context menu to my tray icon, so that when I right-click on the tray icon, it should show me the menu.How should I write the right-click event handler for my tray icon?

I have tried the below:

private void Icon_MouseRightClick(object sender, MouseButtonEventArgs e)
{
 if (e.Button == System.Windows.Forms.MouseButtons.Left)  // shows error ate button
 {
   return;
 }
 if (e.Button == System.Windows.Forms.MouseButtons.Right)
 {
   // code for adding context menu
 }
}

Declared Eventhandler as,

NotifyIcon.MouseRightClick += new MouseButtonEventHandler(NotifyIcon_MouseRightClick);

Answer

piedar picture piedar · Jul 30, 2013

Context menu on right-click is automatic, no need to handle it. Just build your menu and assign it to NotifyIcon.ContextMenu.