Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an icon that is a resource in WPF?

I have a .ico file that is embedded as a resource (build action set to resource). I am trying to create a NotifyIcon. How can I reference my icon?

notifyIcon = new NotifyIcon(); notifyIcon.Icon = ??     // my icon file is called MyIcon.ico and is embedded 
like image 442
ScottG Avatar asked Sep 16 '08 16:09

ScottG


People also ask

How do I add a resource icon?

Just right click on your project-> add-> resource. Add resource window would have popped up where in you can select icon as your preference and select import. Then it lets you to browse through your directory and select your icon.

How do I add a resource to WPF?

To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.

What are resources in WPF?

WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.


2 Answers

Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this:

System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon(); Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream; icon.Icon = new System.Drawing.Icon( iconStream ); 
like image 191
user13125 Avatar answered Sep 27 '22 19:09

user13125


A common usage pattern is to have the notify icon the same as the main window's icon. The icon is defined as a PNG file.

To do this, add the image to the project's resources and then use as follows:

var iconHandle  = MyNamespace.Properties.Resources.MyImage.GetHicon(); this.notifyIcon.Icon = System.Drawing.Icon.FromHandle(iconHandle); 

In the window XAML:

<Window x:Class="MyNamespace.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:local="clr-namespace:Seahorse" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="600" Icon="images\MyImage.png"> 
like image 32
Thomas Bratt Avatar answered Sep 27 '22 18:09

Thomas Bratt