Reputation: 105
I would like to know how I can load a function when form is started?
In this example I would like to launch the function test()
which adds a line to the RichTextBox. I don't want a button and when I try $form1.Show
the form doesn't work.
$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
Upvotes: 0
Views: 4274
Reputation: 54871
The CreateForm
-function will freeze on $form1.ShowDialog()
until the form is closed, so test
will never run. What you can do is add test
as an eventhandler to the Shown-event that is trigged on the first launch of a form.
Replace:
$form1.ShowDialog()
test
with:
$form1.add_Shown({ test } )
$form1.ShowDialog()
You can also run the function before showing the dialog since it only modifies the form anyways (or just do the modifications directly in the form-code):
test
$form1.ShowDialog()
Upvotes: 2