Search code examples
c#notifyicon

How to add event handler for MouseDown event?


Adding the event handler click event was pretty straightforward when I followed the documentation at Microsofts web pages. Unfortunately there was no example including the MouseDown event.

I've tried quite a few combinations but I must be using the wrong syntax or wrong declarations.

This works fine:

    notifyIcon.Click += new System.EventHandler(NotifyIcon_Click);
    System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
    System.Windows.Forms.MenuItem menuItemExit = new System.Windows.Forms.MenuItem();
    
    contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { menuItemExit });

    menuItemExit.Index = 0;
    menuItemExit.Text = "E&xit";
    menuItemExit.Click += new System.EventHandler(menuItemExit_Click);
    notifyIcon.ContextMenu = contextMenu;
}

private void NotifyIcon_Click(object Sender, EventArgs e)
{
    this.Visibility = Visibility.Visible;
    this.Activate();
}

But this does not:

notifyIcon.MouseDown += new System.EventHandler(NotifyIcon_MouseDown);
    
    System.Windows.Forms.ContextMenu contextMenu = new 
    System.Windows.Forms.ContextMenu();

    System.Windows.Forms.MenuItem menuItemExit = new 
    System.Windows.Forms.MenuItem();
    
contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[]{menuItemExit});

    menuItemExit.Index = 0;
    menuItemExit.Text = "E&xit";
    menuItemExit.Click += new System.EventHandler(menuItemExit_Click);
    notifyIcon.ContextMenu = contextMenu;
}

private void NotifyIcon_MouseDown(object Sender, EventArgs e)
{
    this.Visibility = Visibility.Visible;
    this.Activate();
}

enter image description here

What I'm trying to achieve here is for the context menu to open on a right click and the application itself on the left click of the notification icon. I was hoping that on the MouseDown event I would be able to detect whether the left or right mouse button is down.


Solution

  • I suggest you to add event inside page_load event to trigger if its ASP.Net web application.

    protected void Page_Load(object sender, EventArgs e) { }.

    Based on how you have added that event looks correct.

    If this is forms application then you need to handle it inside constructor with syntax as below:

    this.nitifyIcon.MouseDown += new System.Windows.Forms.MouseEventHandler(this.notifyIcon_MouseDown);