Powershell winforms 以子形式引用父级

Powershell winforms reference parent in child form

我在引用子表单中的父表单时遇到困难。 为此,我模拟了一个小片段。我知道我必须将父 属性 分配给子表单,但到目前为止我还没有成功。请指教

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#### PARENT FORM

$date = New-Object System.Windows.Forms.Form
$date.Text = 'Date'
$date.Size = New-Object System.Drawing.Size @(243,230)
$date.StartPosition = 'CenterScreen'

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKbutton.Add_Click({$kibel.showdialog()})
$date.Controls.Add($OKButton)

$date_label = New-Object System.Windows.Forms.Label
$date_label.Location = New-Object System.Drawing.Point(75,70)
$date_label.Size = New-Object System.Drawing.Size(75,23)
$date_label.BorderStyle = 'Fixed3D'
$date_label.Add_Click({$kibel.showdialog()})
$date.Controls.Add($date_label)

##### CHILD FORM

$kibel = New-Object System.Windows.Forms.Form
$kibel.Text = 'Date'
$kibel.Size = New-Object System.Drawing.Size @(243,230)
$kibel.StartPosition = 'CenterScreen'

$kibel_texbox= New-Object System.Windows.Forms.TextBox
$kibel_texbox.Location = New-Object System.Drawing.Point(75,70)
$kibel_texbox.Size = New-Object System.Drawing.Size(75,23)
$kibel.Controls.Add($kibel_texbox)

$kibel_button = New-Object System.Windows.Forms.Button
$kibel_button.Location = New-Object System.Drawing.Point(75,120)
$kibel_button.Size = New-Object System.Drawing.Size(75,23)
$kibel_button.Text = 'KIBEL'
$kibel_button.Add_Click({$kibel.Parent.Controls['date_label'].Text ='done'})
$kibel.Controls.Add($kibel_button)



$date.ShowDialog()

现在我收到 Cannot index into a null array 错误

您需要解决两个问题:

  • 您需要使用Owner属性来指定parent/owning形式
  • 您还没有为 $date_label 控件分配 名称,因此 Controls['date_label'] 不会解析任何内容

第一个问题可以通过将父表单实例分配给子表单上的 Owner 属性 来解决:

$kibel = New-Object System.Windows.Forms.Form
$kibel.Text = 'Date'
$kibel.Size = New-Object System.Drawing.Size @(243,230)
$kibel.StartPosition = 'CenterScreen'
# designate owning form
$kibel.Owner = $date

然后,要命名标签,在定义 $date_label 之后添加:

$date_label.Name = 'date_label'

最后,要通过父窗体正确解析控件,请按如下方式更改 Click 事件处理程序:

$kibel_button.Add_Click({$kibel.Owner.Controls['date_label'].Text ='done'})