zoukankan      html  css  js  c++  java
  • C#获取windows系统的图标

    这个获取关联图标,可以获取磁盘分区的图标,可以获取某个特定类型的文件的图标,也可以获取某个指定文件的图标
    /// <summary> /// 保存文件信息的结构体 /// </summary> /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } class NativeMethods { [DllImport("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags); [DllImport("User32.dll", EntryPoint = "DestroyIcon")] public static extern int DestroyIcon(IntPtr hIcon); #region API 参数的常量定义 public const uint SHGFI_ICON = 0x100; public const uint SHGFI_LARGEICON = 0x0; //大图标 32×32 public const uint SHGFI_SMALLICON = 0x1; //小图标 16×16 public const uint SHGFI_USEFILEATTRIBUTES = 0x10; #endregion } /// <summary> /// 获取文件类型的关联图标 /// </summary> /// <param name="fileName">文件类型的扩展名或文件的绝对路径</param> /// <param name="isLargeIcon">是否返回大图标</param> /// <returns>获取到的图标</returns> static Icon GetIcon(string fileName, bool isLargeIcon) { SHFILEINFO shfi = new SHFILEINFO(); IntPtr hI; if (isLargeIcon) hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_LARGEICON); else hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_SMALLICON); Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon; NativeMethods.DestroyIcon(shfi.hIcon); //释放资源 return icon; }

    private void btnGetIcon_Click(object sender, EventArgs e)
    {
        using (Graphics g = this.pbSmallIcon.CreateGraphics())
        {
            g.Clear(this.pbSmallIcon.BackColor); //清除picturebox的背景色,为了画透明图标
    
            g.DrawIcon(GetIcon(this.tbFileExt.Text, false), 1, 1); //绘制小图标
        }
    
        using (Graphics g = this.pbLargeIcon.CreateGraphics())
        {
            g.Clear(this.pbLargeIcon.BackColor); //清除picturebox的背景色,为了画透明图标
    
            g.DrawIcon(GetIcon(this.tbFileExt.Text, true), 1, 1); //绘制小图标
        }
    }

  • 相关阅读:
    2018/2/26 省选模拟赛 0分
    2018/2/25 省选模拟赛 36分
    BZOJ 2428 JZYZOJ1533 : [HAOI2006]均分数据 模拟退火 随机化
    BZOJ 4036: [HAOI2015]按位或 集合幂函数 莫比乌斯变换 莫比乌斯反演
    BZOJ 3196 Tyvj 1730 二逼平衡树 树套树 线段树 treap
    POJ 2728 JZYZOJ 1636 分数规划 最小生成树 二分 prim
    JZYZOJ1998 [bzoj3223] 文艺平衡树 splay 平衡树
    POJ 3974 Palindrome 字符串 Manacher算法
    BZOJ 1013: [JSOI2008]球形空间产生器sphere 高斯消元
    jQuery cookie使用
  • 原文地址:https://www.cnblogs.com/lihaishu/p/14173141.html
Copyright © 2011-2022 走看看