我有一个.ico文件作为资源嵌入(构建操作设置为资源)。我想创建一个NotifyIcon。如何引用我的图标?
notifyIcon = new NotifyIcon();
notifyIcon.Icon = ?? // my icon file is called MyIcon.ico and is embedded
您的图标文件应该添加到您的项目程序集之一,并将其生成操作设置为资源。在添加对程序集的引用后,您可以像这样创建NotifyIcon:
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 );
常见的使用模式是将通知图标与主窗口的图标相同。这个图标是一个PNG文件。
要实现这一点,将图像添加到项目资源中,然后按以下方式使用:
var iconHandle = MyNamespace.Properties.Resources.MyImage.GetHicon();
this.notifyIcon.Icon = System.Drawing.Icon.FromHandle(iconHandle);
在窗口的 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">
IntPtr iconHandle = Properties.Resources.SystemTray.Handle; my_notifyIcon.Icon = System.Drawing.Icon.FromHandle(iconHandle);
- mickeymicks你不需要使用resx风格资源,只需将ico文件放置在项目文件夹中(假设为“ArtWork”),并在属性中将构建操作设置为“Resources”...
然后,您可以使用PACK URI在XAML中引用它... "pack://application:,,,/Artwork/Notify.ico"
请参见:http://msdn.microsoft.com/en-us/library/aa970069.aspx和示例
如果您想更加符合WPF的风格,您可以查看CodePlex上的WPF Contrib项目,该项目具有一个NotifyIcon控件,您可以在XAML中创建该控件,并且可以使用标准WPF菜单(因此您可以将“任何东西”放在菜单中)。
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="100"
Width="200"
Icon="pack://application:,,,/MyApp;component/Resources/small_icon.ico">
我在这里创建了一个项目,并使用了一个嵌入式资源(构建操作设置为嵌入式资源,而不仅仅是资源)。这个解决方案不能与资源一起使用,但你可能能够操纵它。我将其放在OnIntialized()上,但不一定非要放在那里。
//IconTest = namespace; exclamic.ico = resource
System.IO.Stream stream = this.GetType().Assembly.GetManifestResourceStream("IconTest.Resources.exclamic.ico");
if (stream != null)
{
//Decode the icon from the stream and set the first frame to the BitmapSource
BitmapDecoder decoder = IconBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
BitmapSource source = decoder.Frames[0];
//set the source of your image
image.Source = source;
}