简体   繁体   中英

WinForms Taskbar Icon - Click Event not firing

I have created a non-form c# program that uses the NotifyIcon class.

The text "(Click to Activate)" shows up when I hover the mouse. So I am getting some events handled.

However, The "Click" event does not fire and the Context menu doesnt show up.

public class CTNotify
{
    static NotifyIcon CTicon = new NotifyIcon();
    static ContextMenu contextMenu = new ContextMenu();

    static void Main()
    {
        //Add a notify Icon
        CTicon.Icon = new Icon("CTicon.ico");
        CTicon.Text = "(Click to Activate)";
        CTicon.Visible = true;
        CTicon.Click += new System.EventHandler(CTicon_Click);

        //Create a context menu for the notify icon
        contextMenu.MenuItems.Add("E&xit");

        //Attach context menu to icon
        CTicon.ContextMenu = contextMenu;

        while (true) //Infinite Loop
        {
            Thread.Sleep(300); //wait 
        }
    }

    private static void CTicon_Click(object sender, System.EventArgs e)
    {
        MessageBox.Show("Clicked!");
    }
 }

Why don't you create a form application, and upon initialization just hide the form? I've never had problems with notification icon using this approach

Take a look at the Shell_NotifyIcon() API method, the one that implements a NotifyIcon. Click through to the NOTIFYICONDATA structure. The second member of that structure is a window handle:

A handle to the window that receives notifications associated with an icon in the notification area

You don't have a window and can therefore not receive notifications. You must put the NotifyIcon on a Form. And use Application.Run() to get the notifications and activate the event handlers.

Keep your form hidden by pasting this code:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            this.CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }

I have the same problem, when I use the .hide() event to hide the form or the SetVisibleCore that Hans provide, the click or any mouse events will not fire.

Does someone have another solution ?

PS While the form is visible, everything is working fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM