gpt4 book ai didi

c# - 在 C# 中调整系统图标的大小

转载 作者:行者123 更新时间:2023-11-30 19:40:08 25 4
gpt4 key购买 nike

我想使用 SystemIcons.Warning 但它对我的需要来说太大了。我想调整它的大小。

我试过了:

Icon sizedIcon = new Icon(SystemIcons.Warning, new Size(10,10));

但它不起作用,图标保持不变。

有什么建议吗?

最佳答案

.NET Icon 类相当残缺,由于曾经对 Windows 98 和 Windows 2000 的相关支持,它停留在过去十年。最重要的是,Windows 不支持加载任何大小的系统图标其他 系统的默认图标大小。通常为 32x32。调整它的大小将不可避免地看起来很糟糕。

请记住,任何图标在 10x10 下都不会好看。这只是现代显示器上的一个 Blob 。从接近所需最终大小的图标大小开始,您确实取得了一些进展,所需的调整大小越不剧烈,它看起来仍然合理的可能性就越高。如果可以,请选择图标中可能出现的尺寸。比如 16x16、32x32、48x48。

无论如何,这可以修复的。请记住,这需要相当多的 hack-o-rama,因为 Windows 不直接支持它。需要的是直接从系统 DLL 资源中读取图标。并使用更现代的 winapi LoadImage() 而不是 .NET 使用的 LoadIcon()。适用于 XP 及更高版本。

向您的项目添加一个新类并粘贴此代码:

using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;

public class IconEx : IDisposable {
public enum SystemIcons {
Application = 100,
Asterisk = 104,
Error = 103,
Exclamation = 101,
Hand = 103,
Information = 104,
Question = 102,
Shield = 106,
Warning = 101,
WinLogo = 100
}

public IconEx(string path, Size size) {
IntPtr hIcon = LoadImage(IntPtr.Zero, path, IMAGE_ICON, size.Width, size.Height, LR_LOADFROMFILE);
if (hIcon == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();
attach(hIcon);

}
public IconEx(SystemIcons sysicon, Size size) {
IntPtr hUser = GetModuleHandle("user32");
IntPtr hIcon = LoadImage(hUser, (IntPtr)sysicon, IMAGE_ICON, size.Width, size.Height, 0);
if (hIcon == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();
attach(hIcon);
}


public Icon Icon {
get { return this.icon; }
}

public void Dispose() {
if (icon != null) icon.Dispose();
}

private Icon icon;

private void attach(IntPtr hIcon) {
// Invoke the private constructor so we can get the Icon object to own the handle
var ci = typeof(Icon).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[] { typeof(IntPtr), typeof(bool) }, null);
this.icon = (Icon)ci.Invoke(new object[] { hIcon, true});
}

private const int IMAGE_ICON = 1;
private const int LR_LOADFROMFILE = 0x10;
private const int LR_SHARED = 0x8000;

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadImage(IntPtr hinst, string lpszName, int uType,
int cxDesired, int cyDesired, int fuLoad);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadImage(IntPtr hinst, IntPtr resId, int uType,
int cxDesired, int cyDesired, int fuLoad);
}

示例用法:

    using (var icon = new IconEx(IconEx.SystemIcons.Warning, new Size(10, 10))) {
e.Graphics.DrawIcon(icon.Icon, 0, 0);
}

确实看起来比 SystemIcons.Warning 好。使用 16x16 时非常干净。

关于c# - 在 C# 中调整系统图标的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24695976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com