#region Win32 API
[System.Runtime.InteropServices.DllImport("shell32.dll", EntryPoint
= "ExtractAssociatedIcon")]
private static extern IntPtr
ExtractAssociatedIconA(
IntPtr hInst,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPStr)] string
lpIconPath,
ref int lpiIcon);
[System.Runtime.InteropServices.DllImport("shell32.dll", EntryPoint
= "ExtractIcon")]
private static extern IntPtr ExtractIconA(
IntPtr hInst,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPStr)] string
lpszExeFileName,
int nIconIndex);
private static IntPtr hInst;
#endregion
public
static System.Drawing.Icon ExtractIcon(string fileName, int
index)
{
if (System.IO.File.Exists(fileName) ||
System.IO.Directory.Exists(fileName))
{
System.IntPtr hIcon;
// 文件所含图标的总数
hIcon = ExtractIconA(hInst, fileName, -1);
// 没取到的时候
if (hIcon.Equals(IntPtr.Zero))
{
// 取得跟文件相关的图标
return ExtractAssociatedIcon(fileName);
}
else
{
// 图标的总数
int numOfIcons = hIcon.ToInt32();
if (0 <= index && index <
numOfIcons)
{
hIcon = ExtractIconA(hInst, fileName, index);
if (!hIcon.Equals(IntPtr.Zero))
{
return System.Drawing.Icon.FromHandle(hIcon);
}
else
{
return null;
}
}
else
{
return null;
}
}
}
else
{
return null;
}
}
public static System.Drawing.Icon ExtractAssociatedIcon(string
fileName)
{
if (System.IO.File.Exists(fileName) ||
System.IO.Directory.Exists(fileName))
{
int i = 0;
IntPtr hIcon = ExtractAssociatedIconA(hInst, fileName, ref
i);
if (!hIcon.Equals(IntPtr.Zero))
{
return System.Drawing.Icon.FromHandle(hIcon);
}
else
{
return null;
}
}
else
{
return null;
}
}
●取得代码
string exeFullName =
"F:\\test\\SetIcon\\enDataBaseSetting.exe";
System.Drawing.Icon icon = ExtractIcon(exeFullName,
0);
appIcon = icon.ToBitmap();
●根据实际路径取得图标
System.Drawing.Image appIcon=
System.Drawing.Bitmap.FromFile("F:\\test\\SetIcon\\images2\\App.ico");
●取得资源中的图标(此图标必须在资源【Resource】中存在)
System.IO.Stream stream =
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(PROGRAM_ICON);
System.Drawing.Image appIcon = new
System.Drawing.Bitmap(stream);
●将取得的图标赋给一个按钮
button1.Image = appIcon.GetThumbnailImage(32, 32, null,
IntPtr.Zero);
加载中,请稍候......