XAMLを使わないWPF入門19「ファイルアイコンを取得」

コンピュータ

ファイルの種類にに関連付けられたアプリケーションのアイコンを取得します。

image

ファイル名:NoXAML19FileIcon.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Drawing.Common" Version="10.0.0-preview.6.25358.103" />
  </ItemGroup>

</Project>

ファイル名:App.cs


using System;
using System.Windows;

namespace NoXAML19FileIcon;

public class App : Application
{
    [STAThread]
    public static void Main(string[] args)
    {
        var app = new App();
        app.Run();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var win = new MainWindow();
        win.Show();
    }
}

ファイル名:AssemblyInfo.cs


using System.Windows;

[assembly:ThemeInfo(
    ResourceDictionaryLocation.None,            //where theme specific resource dictionaries are located
                                                //(used if a resource is not found in the page,
                                                // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly   //where the generic resource dictionary is located
                                                //(used if a resource is not found in the page,
                                                // app, or any theme specific resource dictionaries)
)]

ファイル名:MainWindow.cs


using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Interop;

namespace NoXAML19FileIcon;

public class MainWindow : Window
{
    public MainWindow()
    {
        this.Title = "単一ファイルのアイコン表示";
        this.Width = 300;
        this.Height = 300;

        string filePath = @"C:\Windows\notepad.exe"; // ← 任意のファイルに変更

        var iconImage = new System.Windows.Controls.Image
        {
            Source = GetFileIcon(filePath),
            Width = 64,
            Height = 64,
            Margin = new Thickness(10)
        };

        this.Content = iconImage;
    }

    static private BitmapSource? GetFileIcon(string path)
    {
        try
        {
            using (var icon = System.Drawing.Icon.ExtractAssociatedIcon(path))
            {
                if (icon is null) return null;

                return Imaging.CreateBitmapSourceFromHIcon(
                    icon.Handle,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromWidthAndHeight(64, 64));
            }
        }
        catch
        {
            return null;
        }
    }
}

コメント