C# 如何将图标添加到.exe中

-1 c# icons exe tray

如何将 .ico 导入到 C# 中的 .exe 中?(我只想有一个文件)

在资源文件中我有: icon.ico

当我单击该图标时,在属性中我有:“嵌入式资源”

我应该做什么(改变)?

trayIcon.Icon = new Icon("c:\\users\\wulp\\documents\\visual studio 2013\\Projects\\WifiSwitch\\WifiSwitch\\Resources\\icon.ico");
Run Code Online (Sandbox Code Playgroud)

并且,我如何使用相对路径?

谢谢

Mic*_*ael 5

我来到这里寻找有关输出程序集/可执行文件中图标嵌入的书面解决方案。但这个接受的答案并没有真正解释任何事情,除非你知道答案如何与代码作为一个概念相关。对于代码部分,乔纳斯给出的链接也同时失效了。

设置为嵌入资源

但另一种方法是通过右键单击解决方案中的图标文件,将解决方案中的图标文件(最好是)设置为嵌入资源。并将“构建操作”字段设置为“嵌入资源”。默认设置为“内容”,这使得图标文件在 bin/output 文件夹中显示为单独的文件。

然后在运行时通过代码从程序集/可执行文件加载图标。这与乔纳斯可能想要链接的想法略有不同(因为他指的是项目属性中的资源)。

下面的代码的用途是 using System.Drawing; using System.IO; using System.Reflection;

      //note: this = the current windows form I'm setting the icon for, in my case.
        var assembly = Assembly.GetExecutingAssembly();//reflects the current executable
        var resourceName = $"{this.GetType().Namespace}.{this.ProductName}.ico";
        
      //note: this.ProductName reflects the executable's Product name in my solution (see current project, right click it, then click: properties - application - assembly information)

      //reading the source / icon file, in this case from the assembly (as the icon is embedded in here), but the icon can be loaded from anywhere at this point.
        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
        {
            this.Icon = new Icon(stream);
        }
Run Code Online (Sandbox Code Playgroud)

要在快捷方式或任务栏上显示正确的图标,请确保图标文件包含多种尺寸(从 48 像素 x 48 像素到 256 像素 x 256 像素)。否则它会显示一个调整大小/放大的图标。

在应用程序属性级别设置图标

最后,通过右键单击项目(在解决方案资源管理器中)然后单击:属性 - 应用程序来设置项目的图标。在“资源”中选择解决方案中的 .ico 文件。由于它以这种方式嵌入到程序集中,因此不需要在 bin/输出文件夹中复制版本。但我假设输出程序集现在包含两个图标,一个作为嵌入式资源,一个隐藏在程序集字节中的某处...因为遗漏其中之一会破坏图标显示功能,显示默认图标或不加载嵌入式资源图标。这个答案的好处是,作为输入,只有一个图标文件,这最适合维护它。

您计算机上的可能故障是 Windows 的图标缓存

机器的图标缓存可能是一个问题。这主要发生在开发应用程序和切换图标、显示前一个/上一个图标时。在互联网上搜索“重置图标缓存窗口”,或此处的示例https://www.windowscentral.com/how-reset-icon-cache-database-windows-10