views:

220

answers:

2

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!");
    }
 }
+2  A: 

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

Sorantis
+2  A: 

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);
    }
Hans Passant