2010年6月13日日曜日

◆汎用フォームを作る2

PowerShell: ◆汎用フォームをつくるをもう少し汎用的にしてみる。
関数部分を外出しに。

M00Func.ps1
#
#control[0..2]がコントロール配列、control[3]がボタン配列 ##########################################
#
Function MSet-Control($control,$form){
$CWidth,$CHeight = 100,30  #コントロールのサイズ
$BWidth,$BHeight = 50,30   #ボタンのサイズ
$XMargin,$YMargin = 10,10  #コントロールマージン
$ButtonMaxCount = 6        #ボタンの最大数
#Formサイズの設定
$maxControlCount = [Math]::Max([Math]::Max($control[0].Count,$control[1].Count),$control[2].Count)
$formHeight = $maxControlCount * ($CHeight + $XMargin) + ($BHeight + $XMargin)
$formWidth = ($BWidth + $XMargin) * $ButtonMaxCount
$size = New-Object System.Drawing.Size $formWidth,$formHeight
$form.ClientSize = $size
#Formへコントロールの配置
0..2 | %{$XPos = $XMargin}{
$YPos = $XMargin
foreach($cl in $control[$_]){
[System.Windows.Forms.Control]$ctrl = $cl
$ctrl.Left = $XPos
$ctrl.Top = $YPos ; $YPos += ($CHeight + $XMargin)
$ctrl.Width = $CWidth
$ctrl.Height = $CHeight
$form.Controls.Add($ctrl)
}
$XPos += ($CWidth + $XMargin)
}
#Formへボタンの配置
$buttonCount = 1
foreach($button in $control[3]){
$button.Top = $size.Height - $BHeight - $YMargin
$button.Left = $size.Width - ($buttonCount * ($BWidth + $XMargin))
$button.Width = $BWidth
$form.Controls.Add($button)
$buttonCount++
}
}

これは、そのまま抜き出しただけ。
notepad $profile
に登録しても良いかも。

使う側は、
M53汎用Formサンプル.ps1


Set-PSDebug -Strict
 
. (Join-Path (Split-Path $myInvocation.MyCommand.path) M00Func.ps1)  #共通関数の読み込み
 
#[0..2]はコントロール用、3はボタン用
$arr = New-Object System.Collections.ArrayList[] 4
0..3 | %{$arr[$_] = New-Object System.Collections.ArrayList}
 
 
$test1 = New-Object System.Windows.Forms.Label 
$test1.text = "テスト"
[void]$arr[0].Add($test1)
$test2 = New-Object System.Windows.Forms.TextBox
[void]$arr[0].Add($test2)
$test3 = New-Object System.Windows.Forms.TextBox
[void]$arr[0].Add($test3)
$test4 = New-Object System.Windows.Forms.TextBox
[void]$arr[1].Add($test4)
$test5 = New-Object System.Windows.Forms.ComboBox
$test5.Items.AddRange(@("test1","test2","test3"))
[void]$arr[2].Add($test5)
 
$button1 = New-Object System.Windows.Forms.Button
$button1.Text = "閉じる"
$button1.Add_Click({[void] [System.Windows.Forms.MessageBox]::show("フォームを閉じます");$form.Close()})
[void]$arr[3].Add($button1)
 
$form = New-Object System.Windows.Forms.Form
MSet-Control $arr $form  #M00Func.ps1の関数(汎用的にフォームにコントロールを配置する)
 
[void]$form.ShowDialog()

関数を使うためにドットソースで読み込みの指定をする。
. (Join-Path (Split-Path $myInvocation.MyCommand.path) M00Func.ps1)

$myInvocationは自動変数、$myInvocation.MyCommand.pathで自スクリプトのパスが取れる。
共通関数スクリプトは同一フォルダに置く前提。

ArrayListの4つの配列を作るのに、
0..3 | %{$arr[$_] += New-Object System.Collections.ArrayList}

でよさそうに思ったのだが、これではうまくいかない。
$arr.Countが0のまま。
予め定義しておく必要があるみたい。
$arr = New-Object System.Collections.ArrayList[] 4
0..3 | %{$arr[$_] = New-Object System.Collections.ArrayList}

イベントプロシジャは、
$button1.Add_Click({スクリプトブロック})
のように、Add_イベント名 の形式で登録できる。

0 件のコメント:

コメントを投稿