Run Code after Form Load

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 6 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
Datef.SPA
Posts: 1
Last visit: Mon Oct 16, 2017 4:44 am

Run Code after Form Load

Post by Datef.SPA »

Hi,

how is it possible to run code after the Form has been loaded. I tired following sections:

$form1_Load={
#TODO: Initialize Form Controls here
}

if((Show-MainForm_psf) -eq 'OK')
{
}

but noting worked. They start before the Form loadet. I added a button as trigger but thats not the way I want to use it.
Does anyone have a suggestion?

Greetings
User avatar
mxtrinidad
Posts: 399
Last visit: Tue May 16, 2023 6:52 am

Re: Run Code after Form Load

Post by mxtrinidad »

In a multi-form application, I normally a main form call other form(s) using a button(s) in this simple way:

$MainForm_Load={
#TODO: Initialize Form Controls here

}

$buttonCallChildForm_Click={
#TODO: Place custom script here
if((Show-ChildForm_psf) -eq 'OK')
{

}
}

Although, you can do this manually. I suggest you to start using the wizard "File | New | New Form Project" then you can select "Multi Form Project". This Wizard give you the necessary structure to continue building multi-forms apps that can be later become executable program.

Hope this helps!
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Run Code after Form Load

Post by jvierra »

When you ask about running code "after" form is "loaded" I think you mean after the form is "visible" . The event for that is called "Activated". The "Loaded" event only happens before the form is visible.

Add the "Activated" event which occurs each time the form is made the "Active" form. Add a flag field that noted that the first actvation has happened.

Code: Select all

$firsttime = $true
$form1_Activated={
	if($firsttime){
               $script:firsttime = $false
               # other first time code
       }
}
This code - inside the "if" will execute the first time the form is made visible and set the flag that prevents further execution.

The other event is called "Shown" which occurs only the first time the form is shown. and not every time and is the best place to add code for fist time visible. This eliminates the flag. Which one you use depends on what you are trying to do.

Code: Select all

$form1_Shown={
	# first time code here
}
This topic is 6 years and 5 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked