11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WPF フォルダ選択ダイアログ

Posted at

■概要

フォルダ選択ダイアログ。
FolderBrowse0.png

■環境

  • Windows 10
  • Visual Studio 2019
  • .NET Framework 4.8

■準備

NuGetでMicrosoft.WindowsAPICodePack-Shellをインストール。

FolderBrowse1.png

■コード例

MainWindow.xaml
<Window x:Class="FolderBrowse1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FolderBrowse1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="押せ" HorizontalAlignment="Left" Height="67" 
            Margin="235,35,0,0" VerticalAlignment="Top" Width="109" 
            Click="Button_Click"/>
    </Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using MSAPI = Microsoft.WindowsAPICodePack;

namespace FolderBrowse1
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// ボタンクリック時の処理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new MSAPI::Dialogs.CommonOpenFileDialog();

            // フォルダ選択ダイアログ(falseにするとファイル選択ダイアログ)
            dlg.IsFolderPicker = true;
            // タイトル
            dlg.Title = "フォルダを選択してください";
            // 初期ディレクトリ
            dlg.InitialDirectory = @"D:\Work";

            if (dlg.ShowDialog() == MSAPI::Dialogs.CommonFileDialogResult.Ok)
            {
                MessageBox.Show($"{dlg.FileName}が選択されました。");
            }
        }
    }
}

■実行

FolderBrowse2.png

FolderBrowse3.png

FolderBrowse4.png

11
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?