在Form的开始加载函数

时间:2017-03-20 17:09:08

标签: winforms powershell

我想知道在启动表单时如何加载函数?

在这个例子中,我想启动函数test(),它向RichTextBox添加一行。我不想要一个按钮,当我尝试$form1.Show时,表单不起作用。

$ErrorActionPreference = 'Continue'

Function test {
  $richtextbox1.AppendText("testttt `n")
}

function CreateForm {
  Add-Type -AssemblyName System.Windows.Forms
  Add-Type -AssemblyName System.Drawing

  $form1 = New-Object System.Windows.Forms.Form

  #Form Parameter
  $form1.Text = ""
  $form1.Name = ""
  $System_Drawing_Size = New-Object System.Drawing.Size
  $System_Drawing_Size.Width = 600
  $System_Drawing_Size.Height = 500
  $form1.ClientSize = $System_Drawing_Size
  $Form1.MinimizeBox = $false
  $Form1.MaximizeBox = $true
  $form1.ControlBox = $true
  $form1.Topmost = $true
  $Form1.AutoSize = $true
  $Form1.ShowInTaskbar = $false
  $form1.StartPosition = "CenterScreen"

  $label1 = New-Object System.Windows.Forms.Label
  $label1.Location = New-Object System.Drawing.Point(200, 40)
  $label1.Size = New-Object System.Drawing.Size(400, 40)
  $label1.Text = ""
  $label1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 18, [System.Drawing.FontStyle]::Bold)
  $form1.Controls.Add($label1)

  $label2 = New-Object System.Windows.Forms.Label
  $label2.Location = New-Object System.Drawing.Point(50, 125)
  $label2.Size = New-Object System.Drawing.Size(400, 40)
  $label2.Text = "Step : "
  $label2.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 18, [System.Drawing.FontStyle]::Bold)
  $form1.Controls.Add($label2)

  $label3 = New-Object System.Windows.Forms.Label
  $label3.Location = New-Object System.Drawing.Point(50, 175)
  $label3.Size = New-Object System.Drawing.Size(400, 40)
  $label3.Text = " in Progress"
  $label3.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 18, [System.Drawing.FontStyle]::Bold)
  $form1.Controls.Add($label3)

  $richTextBox1 = New-Object System.Windows.Forms.RichTextBox
  $richTextBox1.Location = New-Object System.Drawing.Point(50, 250)
  $richTextBox1.Size = New-Object System.Drawing.Size(500, 200)
  $richTextBox1.Text = " : `n"
  $richTextBox1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 18, [System.Drawing.FontStyle]::Bold)
  $form1.Controls.Add($richTextBox1)

  $InitialFormWindowState = $form1.WindowState
  #Show the Form

  $form1.ShowDialog()
  test
}

CreateForm

1 个答案:

答案 0 :(得分:2)

CreateForm - 函数将冻结$form1.ShowDialog(),直到表单关闭,因此test永远不会运行。您可以做的是将test作为事件处理程序添加到Shown - 首次启动表单时触发的事件。

替换:

$form1.ShowDialog()
test

使用:

$form1.add_Shown({ test } )
$form1.ShowDialog()

您也可以在显示对话框之前运行该函数,因为它只会修改表单(或者直接在表单代码中进行修改):

test
$form1.ShowDialog()