我有一个作为资源嵌入的 .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">

好吧,你不想使用 resx 风格的资源:您只需将 ico 文件粘贴到项目中的一个文件夹中(假设为“ArtWork”),然后在属性中将“构建操作”设置为“资源”...

然后您可以使用 PACK URI 在 XAML 中引用它...“包://应用程序:,,,/Artwork/Notify.ico”

看这里: http://msdn.microsoft.com/en-us/library/aa970069.aspx样本

如果你想多一点...类似 WPF,你应该看看 WPF 贡献 CodePlex 上的项目,其中有一个 NotifyIcon 控件,您可以在 XAML 中创建该控件,并使用标准 WPF 菜单(因此您可以在菜单中粘贴“任何内容”)。

如果您只是在寻找简单的答案,我认为这就是 MyApp 是您的应用程序名称以及应用程序的根命名空间名称的地方。您必须使用 pack URI 语法,但从嵌入资源中提取图标并不需要那么复杂。

    <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;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top