从代码隐藏或在 XAML 中在 NotifyIcon 控件中设置图像

从代码隐藏或在 XAML 中在 NotifyIcon 控件中设置图像

问题描述:

我正在使用 WindowsForms 中的 NotifyIcon,因为在 WPF 中我们没有这样的控制,但是 WinForms 中的一个工作正常,我的问题只是当图像在项目中时将图像设置为 NotifyIcon 中的图标.

i am using the NotifyIcon from WindowsForms because in WPF we don't have such control, but the one from WinForms works fine, my problem is only setting an image as icon in the NotifyIcon when the image is in the Project.

我的项目中有一个名为 Images 的文件夹中的图像,图像文件名为notification.ico".

I have the image in a folder called Images in my Project, the image file calls 'notification.ico'.

这是我的通知图标:

System.Windows.Forms.NotifyIcon sysIcon = new System.Windows.Forms.NotifyIcon() 
{
    Icon = new System.Drawing.Icon(@"/Images/notification.ico"),
    ContextMenu = menu,
    Visible = true
};

我在这里做错了什么?

我可以在 XAML 中而不是在代码隐藏中创建我的 NotifyIcon 吗?如果可能,我该怎么做?

And can i create my NotifyIcon in XAML instead in Code Behind? If it's possible, how can i do it?

提前致谢!

System.Drawing.Icon 不支持用于 WPF 的 pack:// URI 方案资源.您可以:

System.Drawing.Icon doesn't support the pack:// URI scheme used for WPF resources. You can either:

  • 将您的图标作为嵌入资源包含在 resx 文件中,并直接使用生成的属性:

  • include your icon as an embedded resource in a resx file, and use the generated property directly:

System.Windows.Forms.NotifyIcon sysIcon = new System.Windows.Forms.NotifyIcon() 
{
    Icon = Properties.Resources.notification,
    ContextMenu = menu,
    Visible = true
};

  • 或者像这样从 URI 手动加载它:

  • or load it manually from the URI like this:

    StreamResourceInfo sri = Application.GetResourceStream(new Uri("/Images/notification.ico"));
    System.Windows.Forms.NotifyIcon sysIcon = new System.Windows.Forms.NotifyIcon() 
    {
        Icon = new System.Drawing.Icon(sri.Stream),
        ContextMenu = menu,
        Visible = true
    };