如何使用WPF中作为资源的图标?
时间:2020-03-05 18:56:32 来源:igfitidea点击:
我有一个.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 );
回答
好吧,我们不想使用resx样式资源:我们只需将ico文件粘贴到项目中的文件夹中(让我们说" ArtWork"),然后在属性中,将"构建操作"设置为"资源" ...
然后,我们可以使用PACK URI在XAML中引用它..." pack:// application:, / Artwork / Notify.ico"
参见此处:http://msdn.microsoft.com/zh-cn/library/aa970069.aspx和示例
如果我们想要更多... WPF之类的东西,则应查看CodePlex上的WPF Contrib项目,该项目具有一个NotifyIcon控件,可以在XAML中创建该控件,并使用标准WPF菜单(因此我们可以粘贴" ")。
回答
我在这里创建了一个项目,并使用了嵌入式资源(将构建操作设置为"嵌入式资源",而不仅仅是"资源")。该解决方案不适用于Resource,但是我们可以操纵它。我把它放在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; }
回答
一种常见用法是使通知图标与主窗口的图标相同。该图标定义为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">