ExtractAssociatedIcon


ファイルのアイコンを取得する場合は、ExtractAssociatedIcon関数をつかいます(Icon.ExtractAssociatedIcon メソッド (String))。しかし、ネットワークドライブに保存されているファイルのアイコンを取得しようとして、

Icon MyIcon = Icon.ExtractAssociatedIcon("\\hoge\aaa\bbb.txt");

と書いてもアイコンが取得できません。この場合はWindows APIを直接叩く必要があります。

ExtractAssociatedIconでネットワーク上のファイルのICONが取得できないに記載されていたコードをC#で書き直してみると、以下のような感じになります。

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

public class HogeClass
{

  [DllImport("shell32.dll", EntryPoint = "ExtractAssociatedIcon")]
  private extern static IntPtr ExtractAssociatedIcon(
      IntPtr hInst,
      [MarshalAs(UnmanagedType.LPStr)] string lpIconPath,
      ref int lpiIcon);

  private static Image GetIcon(String FilePath)
  {
    IntPtr hInst = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
    Int32 iIcon = 0;
    IntPtr hIcon;

    hIcon = ExtractAssociatedIcon(hInst, FilePath, ref iIcon);

    return Icon.FromHandle(hIcon).ToBitmap();
  }
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください