2017年11月19日

【PowerShell】Windowsフォームにテキストボックスを表示して入力できるようにする


前回、『Windowsフォームを作成する』でWindowsフォームの表示をしてみましたが、今回は、Windowsフォームにテキストボックスを表示して入力できるようにしてみました。

まあ、マイクロソフトの下記のサイトのコードをほぼパクッてるんですが、テキストボックスをマルチラインにしたり若干アレンジを加えてますのでよかったら参考にしてみてください。
https://docs.microsoft.com/ja-jp/powershell/scripting/getting-started/cookbooks/creating-a-custom-input-box?view=powershell-5.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
}

実行結果








スポンサーリンク



Follow Me on Pinterest
Clip to Evernote