Set system tray notifyicon.icon to a pic in images folder

Rob picture Rob · Jun 3, 2013 · Viewed 11.3k times · Source

I've tried several things and eventualy just put the image directly inside C:\Users\Gebruiker\Documents\Visual Studio 2012\Projects\FolderMonitor\FolderMonitor\bin\Debug. This works for now, but idealy I'd like to set the notifyIcon.Icon = new Icon("folder.ico") to an image inside a images folder in the solution. But I can't figure out how this works..

    public FolderMonitorApplicationContext()
    {
        this.monitor =  new Monitor();

        notifyIcon = new NotifyIcon();
        notifyIcon.Icon = new Icon("folder.ico");
        notifyIcon.Text = "Folder Monitor";
        notifyIcon.Visible = true;

        contextMenu = new ContextMenuStrip();
        openMonitor = new ToolStripMenuItem();
        exitApplication = new ToolStripMenuItem();

        notifyIcon.ContextMenuStrip = contextMenu;

        notifyIcon.DoubleClick += NotifyIcon_DoubleClick;

        openMonitor.Text = "Open";
        openMonitor.Click += new EventHandler(OpenMonitor_Click);
        contextMenu.Items.Add(openMonitor);

        exitApplication.Text = "Exit..";
        exitApplication.Click += new EventHandler(ExitApplication_Click);
        contextMenu.Items.Add(exitApplication);
    }

So it's currently working, but not how it i'd like it to work. Hope you can help me out here, thanks in advance.

Answer

Dan picture Dan · Jun 3, 2013

After adding the picture file to your project, bring up the item properties by clicking on it, and pressing F4. Under Build Action, change it to "Embedded Resource".

You can access embedded resources in Stream form like this:

public FolderMonitorApplicationContext()
{
    this.monitor =  new Monitor();

    notifyIcon = new NotifyIcon();
    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
        "<project namespace>.<folder path>" + "filename.ico"))
    {
        notifyIcon.Icon = new Icon(stream);
    }

    notifyIcon.Text = "Folder Monitor";
    notifyIcon.Visible = true;

    contextMenu = new ContextMenuStrip();
    openMonitor = new ToolStripMenuItem();
    exitApplication = new ToolStripMenuItem();

    notifyIcon.ContextMenuStrip = contextMenu;

    notifyIcon.DoubleClick += NotifyIcon_DoubleClick;

    openMonitor.Text = "Open";
    openMonitor.Click += new EventHandler(OpenMonitor_Click);
    contextMenu.Items.Add(openMonitor);

    exitApplication.Text = "Exit..";
    exitApplication.Click += new EventHandler(ExitApplication_Click);
    contextMenu.Items.Add(exitApplication);
}