C# WinForm 把系统图标放到 Button(两种方案)
说明:Windows系统自带DLL(imageres.dll / shell32.dll)里没有动物头像,只有文件夹、警告、信息、磁盘等系统图标;动物头像需要自己准备图片资源。下面先讲系统内置图标调用。
前置引用
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
方案1:直接用 SystemIcons(最简单,内置系统图标)
SystemIcons 是 .NET 自带,不用P/Invoke,直接拿到警告、信息、问号、错误等系统图标,赋值给按钮 Image 属性。
// 窗体构造函数
public Form1()
{
InitializeComponent();
// 取系统【信息】图标,转成位图放到按钮
Icon sysIcon = SystemIcons.Information;
button1.Image = sysIcon.ToBitmap();
button1.ImageAlign = ContentAlignment.MiddleLeft;
button1.TextImageRelation = TextImageRelation.ImageBeforeText;
button1.Text = "信息按钮";
}
可用枚举:
SystemIcons.Application、Error、Warning、Information、Question、Shield、WinLogo
方案2:从 imageres.dll / shell32.dll 提取任意系统图标(PInvoke ExtractIconEx)
Windows现代图标大多在 C:\Windows\System32\imageres.dll,旧版在 shell32.dll,通过索引提取图标。
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phIconLarge, out IntPtr phIconSmall, int nIcons);
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);
/// <summary>从dll提取图标</summary>
/// <param name="dllPath">imageres.dll</param>
/// <param name="index">图标索引</param>
/// <returns>Icon对象</returns>
private Icon ExtractDllIcon(string dllPath, int index)
{
IntPtr hLarge, hSmall;
int ret = ExtractIconEx(dllPath, index, out hLarge, out hSmall, 1);
if (ret <= 0) return null;
Icon icon = Icon.FromHandle(hLarge);
DestroyIcon(hLarge);
DestroyIcon(hSmall);
return icon;
}
// 使用示例
private void Form1_Load(object sender, EventArgs e)
{
string dll = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"System32\imageres.dll");
Icon folderIcon = ExtractDllIcon(dll, 3); // index=3 文件夹图标,索引可查imageres图标表
button2.Image = folderIcon.ToBitmap();
button2.ImageAlign = ContentAlignment.MiddleLeft;
button2.TextImageRelation = TextImageRelation.ImageBeforeText;
button2.Text = "文件夹";
}
工具推荐:Resource Hacker 打开
imageres.dll,浏览所有图标,查看每个图标的索引编号。
动物头像怎么放到按钮
系统DLL没有动物头像,两种办法:
-
下载动物png/ico图片,加入项目资源(项目属性→资源,添加图片)
// 资源里的动物图
button3.Image = Properties.Resources.cat;
button3.TextImageRelation = TextImageRelation.ImageBeforeText; -
代码加载本地图片文件
button3.Image = Image.FromFile(@"c:\cat.png");
WPF版本(如果你是WPF)
WPF按钮不用Bitmap,用BitmapImage
<Button Width="120" Height="40">
<StackPanel Orientation="Horizontal">
<Image Width="20" Height="20">
<Image.Source>
<BitmapImage UriSource="pack://application:,,,/Resources/cat.png"/>
</Image.Source>
</Image>
<TextBlock Margin="5,0,0,0">动物按钮</TextBlock>
</StackPanel>
</Button>
常见坑
- 图标用完记得释放GDI句柄,否则内存泄漏;
- .NET6/.NET7+ WinForm 要手动安装
System.Drawing.CommonNuGet包; - 64位系统,读取System32下dll,32位程序会被重定向到SysWOW64,提取图标会不对,项目平台目标设为x64。
如果你需要,我可以给你一份imageres.dll常用图标索引清单,或者写一个遍历imageres所有图标预览窗体。