LoginSignup
30
34

More than 3 years have passed since last update.

PowerShellメモ GUIの入力画面を表示(XAML)

Last updated at Posted at 2016-10-17

概要

GUIの入力画面を表示するサンプル。
00.png

コード

Add-Type -AssemblyName PresentationFramework
[xml]$xaml = @'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="入力画面">
<StackPanel>
  <TextBlock Text="日付を入力↓" />
  <StackPanel Orientation="Horizontal">
    <DatePicker Name="cal" />
    <TextBlock Text="{Binding ElementName=cal, Path=SelectedDate, StringFormat='選択した日付:yyyy/MM/dd', Mode=OneWay}" Margin="20,0,0,0" />
  </StackPanel>
  <TextBlock Text="テキストを入力↓" Margin="0,10,0,0" />
  <TextBox Name="inTxt" Text=""/>
  <CheckBox Name="chk" Content="チェック" IsChecked="True" Margin="0,10,0,0" />
  <Button Name="okButton" Content="OK" IsDefault="True" Margin="0,10,0,0" />
  <TextBlock Name="errTxt" Text="" Foreground="Red" Margin="0,20,0,0" />
</StackPanel>
</Window>
'@
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)

$calendar1 = $window.FindName("cal")
$inputText1 = $window.FindName("inTxt")
$checkbox1 = $window.FindName("chk")
$btn1 = $window.FindName("okButton")
$errorText1 = $window.FindName("errTxt")

# カレンダーの初期設定(過去の日付を選択不可にする)
$calendar_loaded = $calendar1.add_Loaded
$calendar_loaded.Invoke({
  $calendar1.BlackoutDates.AddDatesInPast()
})

# 実行ボタン押下時の処理
$btn_clicked = $btn1.add_Click
$btn_clicked.Invoke({
  # 入力チェック
  if ($calendar1.SelectedDate -eq $null)
  {
      $errorText1.Text = "日付を入力してください。"
      return
  }
  if ($inputText1.Text -eq "")
  {
      $errorText1.Text = "テキストを何か入力してください。"
      return
  }

  # 入力値をコンソールに表示
  [string]$str1 = $calendar1.SelectedDate.ToString("yyyy/MM/dd")
  [string]$str2 = $inputText1.Text
  [string]$str3 = $checkbox1.IsChecked.ToString()
  Write-Host "日付:${str1}、テキスト:${str2}、チェック:${str3}" -BackgroundColor Blue
  # ウィンドウを閉じる
  $window.Close()
})

# ウィンドウ表示
$window.ShowDialog() > $null

実行例

ps05.png

日付を選択。
ps06.png

日付とテキストを入力したらOKボタンを押す。
ps07.png

ダイアログが閉じてコンソールにメッセージが出力される。
ps08.png

動作確認した環境

  • PowerShell V4 (Windows 8.1)
  • PowerShell V5 (Windows 10)
30
34
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
30
34