小智 47
在项目属性>应用程序>图标和清单>浏览*.ico文件并将其添加到那里.
在_Load
Form 的构造函数或事件中,只需添加:
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
Run Code Online (Sandbox Code Playgroud)除了Marc的建议之外,您可能希望表单自动继承包含/调用它们的正在执行的程序集的图标.
这可以通过将以下代码添加到您继承的表单来完成:
public MyCustomForm()
{
Icon = GetExecutableIcon();
}
public Icon GetExecutableIcon()
{
IntPtr large;
IntPtr small;
ExtractIconEx(Application.ExecutablePath, 0, out large, out small, 1);
return Icon.FromHandle(small);
}
[DllImport("Shell32")]
public static extern int ExtractIconEx(
string sFile,
int iIndex,
out IntPtr piLargeVersion,
out IntPtr piSmallVersion,
int amountIcons);
Run Code Online (Sandbox Code Playgroud)
这就是为所有表单设置同一个图标而不必一一更改的方法。这是我在我的应用程序中编码的内容。
FormUtils.SetDefaultIcon();
Run Code Online (Sandbox Code Playgroud)
这是一个可以使用的完整示例。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Here it is.
FormUtils.SetDefaultIcon();
Application.Run(new Form());
}
}
Run Code Online (Sandbox Code Playgroud)
这是 FormUtils 类:
using System.Drawing;
using System.Windows.Forms;
public static class FormUtils
{
public static void SetDefaultIcon()
{
var icon = Icon.ExtractAssociatedIcon(EntryAssemblyInfo.ExecutablePath);
typeof(Form)
.GetField("defaultIcon", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)
.SetValue(null, icon);
}
}
Run Code Online (Sandbox Code Playgroud)
这里是 EntryAssemblyInfo 类。对于此示例,这被截断了。这是我从 System.Winforms.Application 中获取的自定义编码类。
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Diagnostics;
public static class EntryAssemblyInfo
{
private static string _executablePath;
public static string ExecutablePath
{
get
{
if (_executablePath == null)
{
PermissionSet permissionSets = new PermissionSet(PermissionState.None);
permissionSets.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
permissionSets.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
permissionSets.Assert();
string uriString = null;
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly == null)
uriString = Process.GetCurrentProcess().MainModule.FileName;
else
uriString = entryAssembly.CodeBase;
PermissionSet.RevertAssert();
if (string.IsNullOrWhiteSpace(uriString))
throw new Exception("Can not Get EntryAssembly or Process MainModule FileName");
else
{
var uri = new Uri(uriString);
if (uri.IsFile)
_executablePath = string.Concat(uri.LocalPath, Uri.UnescapeDataString(uri.Fragment));
else
_executablePath = uri.ToString();
}
}
return _executablePath;
}
}
}
Run Code Online (Sandbox Code Playgroud)