LoginSignup
2
3

C#でWinRTダイアログを呼び出す

Last updated at Posted at 2024-05-01

環境

Windows 11 Pro (64bit)
Visual Studio Community 2022

MessageDialog

適当なプロジェクト名のディレクトリを用意する。
例:C:\Projects\.NET\MsgDlgSample

dotnet new console
MsgDlgSample.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

WinRTを使うためTargetFrameworkをnet8.0-windows10.0.22000.0とする。

Program.cs
using Windows.UI.Popups;
using WinRT.Interop;

var dlg = new MessageDialog("hello, world");
InitializeWithWindow.Initialize(dlg, 0x10010);
await dlg.ShowAsync();

0x10010はDesktopWindowのハンドル。

ビルドと実行。

dotnet build
bin\Debug\net8.0-windows10.0.22000.0\MsgDlgSample.exe

FileOpenPicker

適当なプロジェクト名のディレクトリを用意する。
例:C:\Projects\.NET\PickerSample

dotnet new wpf
PickerSample.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>

</Project>

WinRTを使うためTargetFrameworkをnet8.0-windows10.0.22000.0とする。

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using Windows.Storage.Pickers;
using WinRT.Interop;

namespace PickerSample;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    	var btn = new Button();
    	btn.Content = "hoge";
    	btn.Click += btn_Click;
    	Content = btn;
    }

	async void btn_Click(object sender, RoutedEventArgs e)
	{
		var picker = new FileOpenPicker();

		var hWnd = new WindowInteropHelper(this).Handle;
		InitializeWithWindow.Initialize(picker, hWnd);

		picker.FileTypeFilter.Add("*");
		var file = await picker.PickSingleFileAsync();
		if (file != null) {
			((Button)sender).Content = file.Path;
		}
	}
}

ビルドと実行。

dotnet build
bin\Debug\net8.0-windows10.0.22000.0\PickerSample.exe
2
3
0

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
2
3