C#のWinFormsでシステムアイコンを読み込むサンプル

コンピュータ

SHELL32.dll内にシステムアイコンが埋め込まれているので、そちらからアイコンを取り出して表示するサンプルになります。

プロジェクトの作成

.Net SDKのバージョン8

mkdir SystemIconSample
cd SystemIconSample
dotnet new winforms

ソースコード

ファイル名:IconManager.cs

public class IconManager
{
    static public Icon? GetSystemIcom(int no, int size=64)
    {
        Icon? result = null;
        string systemRoot = Environment.GetEnvironmentVariable("SystemRoot") ?? @"C:\Windows";
        string dllPath = Path.Join(systemRoot, @"System32\SHELL32.dll");

        // dllファイルの有無を確認
        if (!File.Exists(dllPath)) return result;

        // dllからアイコンを取り出し戻す。
        return Icon.ExtractIcon(dllPath, no, size);
    }
}

ファイル名:Form1.cs

using System.Diagnostics;

namespace SystemIconSample;

public partial class Form1 : Form
{
    PictureBox picbox1 = new()
    {
        Dock = DockStyle.Fill,
        SizeMode = PictureBoxSizeMode.CenterImage,
    };
    public Form1()
    {
        InitializeComponent();

        Controls.Add(picbox1);

        Load += Form1_Load;
    }
    void Form1_Load(Object? sender, EventArgs e)
    {
        var icon = IconManager.GetSystemIcom(32, 256);

        if (icon is null) return;
        picbox1.Image?.Dispose();
        picbox1.Image = icon.ToBitmap();
    }
}
ソースコードのダウンロード

実行

成功するとゴミ箱のアイコンが表示されます。

ファイルとフォルダーアイコン

namespace IconManager01;

public class IconManager
{
    static string _systemDir = Environment.GetFolderPath(Environment.SpecialFolder.System);
    static string shell32Path = Path.Combine(_systemDir, "shell32.dll");
    static public Icon? GetSystemIcon(int index, int size)
    {
        Icon? result = null;

        if (!File.Exists(shell32Path)) return result;
        try
        {
            return Icon.ExtractIcon(shell32Path, index, size);
        }
        catch
        {
            return null;
        }
    }
    // フォルダーアイコン
    static Icon? _folderIcon;
    static public Icon? GetFolderIcon()
    {
        const int size = 64;

        if (_folderIcon is null)
        {
            _folderIcon = GetSystemIcon(3, size);
        }
        return _folderIcon;
    }
    // ファイルアイコン
    static Icon? _fileIcon;
    static public Icon? GetFileIcon()
    {
        const int size = 64;

        if (_fileIcon is null)
        {
            _fileIcon = GetSystemIcon(0, size);
        }
        return _fileIcon;
    }
}

public partial class Form1 : Form
{
    PictureBox _picbox = new()
    {
        Dock = DockStyle.Fill,
        SizeMode = PictureBoxSizeMode.CenterImage,
    };

    public Form1()
    {
        InitializeComponent();

        this.Controls.Add(_picbox);

        _picbox.Image = IconManager.GetFolderIcon()?.ToBitmap();

        _picbox.Click += (sender, e) =>
        {
            _picbox.Image?.Dispose();
            _picbox.Image = IconManager.GetFileIcon()?.ToBitmap();
        };
    }
}

コメント