Accessing resources from code to install NotifyIcon.Icon

I am trying to get the NotifyIcon icon in WPF.

So, I added the .ico file to my solution in the Resources folder and set the build action to Resource .

I am trying to grab this resource in code like this:

var icon = (Icon) Application.Current.FindResource("/Resources/icon.ico")

This does not work.

In addition to this: Application.Current.Resources.Count returns 0 .

EDIT

var i = new Icon(Application.GetResourceStream(new Uri("/systemtrayicon.ico", UriKind.Relative)).Stream);

The root icon and assembly action are set to Resource .

Still not working.

EDIT AGAIN:

I needed to clear the solution and rebuild according to: WPF throws a "Unable to find resource" exception when loading an image

+6
source share
2 answers

You need to pass the name of the resource as a parameter to the FindResource method, not the path to the resource. A sample code would look like this:

 var icon = (Icon) Application.Current.FindResource("myImage") 

Note that in the above code example, "myImage" is the name of the resource.

Refer to the Application.FindResource Method on MSDN.

You say: Application.Current.Resources.Count is zero, this means that you do not have the resources defined in your App.xaml file.

You can add resources to App.xaml as follows:

 <Application.Resources> <Image x:Key="myImage" Source="img.png" /> </Application.Resources> 

It looks like your icon is an embedded resource. FindResource cannot work with embedded resources. Set the BuildAction your icon to Resource .

Refer to this page to learn more about WPF resources.

UPDATE

Code for accessing embedded resources

 Assembly.GetExecutingAssembly().GetManifestResourceStream("myImg.png"); 

However, if you added this image to Resource.Resx, you should just use Resources.ResourceName .

UPDATE 2

Adding resources to App.xaml or any ResourceDictionary is better, so you can use them as static / dynamic resources using the StaticResource or DynamicResource markup DynamicResource .

If you do not want to add it to App.xaml resources and still want to access it, one option, as I mentioned above, is to add it to Resources.Resx and use Resources.ResourceName to link to the icon / image

Another way is to create System.Drawing.Icon yourself, a sample code:

 new System.Drawing.Icon(Application.GetResourceStream(new Uri("/Resources/icon.ico"))); 

Personally, I would go with XAML resources and add them to App.xaml or ResourceDictionary.

+7
source

It will work 100%

 ni.Icon = new Icon(Application.GetResourceStream(new Uri("pack://application:,,,<Image Location From root>")).Stream); 

Example:

 notify.Icon = new Icon(Application.GetResourceStream(new Uri("pack://application:,,,/images/favicon.ico")).Stream); 
+12
source

Source: https://habr.com/ru/post/959318/


All Articles