potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

C# SHObjectProperties関数を使用してファイル、プリンター、ボリュームのプロパティダイアログを開く

概要

C#でファイル、プリンター、ボリュームのプロパティダイアログを開く方法にはSHFileOperationEx関数、IShellFolderインターフェイスとIContextMenuインターフェイス等がありますが、SHObjectProperties関数を使用することでより簡単に実現することができます。ただし、SHObjectProperties関数はWindows XP/Windows Server 2003以上(デスクトップアプリケーション)でしか実装されていません。

以下ではSHObjectProperties関数を使用したサンプルコードを紹介します。

サンプルコード

ファイル(C:\Windows)とプリンター(最初に見つかったプリンター)のプロパティを表示するサンプルコードです。GUIDパスを指定したボリュームのプロパティ表示にはGUIDパスの取得が別途必要となります。

using System;
using System.Drawing.Printing; // プリンターの列挙に必要
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            // プリンタのプロパティ
            var printers = PrinterSettings.InstalledPrinters;
            if (printers.Count != 0)
            {
                Utility.ShowObjectProperties(
                    ObjectPropertiesObjectType.PrinterName,
                    printers[0]);
            }

            // ファイルのプロパティ
            Utility.ShowObjectProperties(
                ObjectPropertiesObjectType.FilePath,
                @"C:\Windows");
        }
    }

    public static class Utility
    {
        private static class NativeMethods
        {
            [DllImport("shell32.dll")]
            public static extern bool SHObjectProperties(
                IntPtr hwnd,
                uint shopObjectType,
                [MarshalAs(UnmanagedType.LPWStr)] string pszObjectName,
                [MarshalAs(UnmanagedType.LPWStr)] string pszPropertyPage);
        }

        public static bool ShowObjectProperties(
            ObjectPropertiesObjectType objectType,
            string objectName,
            string pageName = null,
            IntPtr windowHandle = default(IntPtr))
        {
            return NativeMethods.SHObjectProperties(
                windowHandle,
                (uint)objectType,
                objectName,
                pageName);
        }
    }

    public enum ObjectPropertiesObjectType : uint
    {
        // プリンタのフレンドリーネーム SHOP_PRINTERNAME
        PrinterName = 0x00000001,
        // 絶対パス SHOP_FILEPATH
        FilePath = 0x00000002,
        // ボリュームGUID SHOP_VOLUMEGUID
        VolumeGUID = 0x00000004
    }
}

参考

2021/3/10:この記事は別のブログで投稿した記事を移動したものです。