前回、『Windowsフォームを作成する』でWindowsフォームの表示をしてみましたが、今回は、Windowsフォームにテキストボックスを表示して入力できるようにしてみました。
まあ、マイクロソフトの下記のサイトのコードをほぼパクッてるんですが、テキストボックスをマルチラインにしたり若干アレンジを加えてますのでよかったら参考にしてみてください。
https://docs.microsoft.com/ja-jp/powershell/scripting/getting-started/cookbooks/creating-a-custom-input-box?view=powershell-5.1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#フォーム
$form = New-Object System.Windows.Forms.Form
$form.Text = "入力フォーム作成テスト"
$form.Size = New-Object System.Drawing.Size(400,240)
$form.StartPosition = "CenterScreen"
#ラベル
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,20)
$label.Size = New-Object System.Drawing.Size(340,20)
$label.Text = "何か入力してください"
$form.Controls.Add($label)
#テキストボックス
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(20,40)
$textBox.Multiline = $True
$textBox.AcceptsReturn = $True
$textBox.AcceptsTab = $True
$textBox.WordWrap = $True
$textBox.ScrollBars = [System.Windows.Forms.ScrollBars]::Vertical
$textBox.Anchor = (([System.Windows.Forms.AnchorStyles]::Left) `
-bor ([System.Windows.Forms.AnchorStyles]::Top) `
-bor ([System.Windows.Forms.AnchorStyles]::Right) `
-bor ([System.Windows.Forms.AnchorStyles]::Bottom))
$textBox.Size = New-Object System.Drawing.Size(340,100)
$form.Controls.Add($textBox)
#OKボタン
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(200,160)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Anchor = (([System.Windows.Forms.AnchorStyles]::Right) `
-bor ([System.Windows.Forms.AnchorStyles]::Bottom))
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
#キャンセルボタン
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(285,160)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Anchor = (([System.Windows.Forms.AnchorStyles]::Right) `
-bor ([System.Windows.Forms.AnchorStyles]::Bottom))
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
#フォームを常に手前に表示
$form.Topmost = $True
#フォームをアクティブにし、テキストボックスにフォーカスを設定
$form.Add_Shown({$textBox.Select()})
#フォームを表示
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
#OKボタンが押された場合、テキストボックスの内容を取得
$x = $textBox.Text
$x
}
実行結果

スポンサーリンク