Category Archives: Forms

Script: Close form after certain time

I use this to create time-limited splash screens I then display during various other scripts I run to keep the end user informed. The beauty of this one is that is there is no DialogResult i.e OK, Yes or Cancel when the form is closed, therefore no annoying pop-up messages when the script is run in GUI-only mode (text corrected 09/05/17).
function Splash1 {
[System.Windows.forms.Application]::EnableVisualStyles()
$form1 = New-Object ‘System.Windows.forms.form’
$label1 = New-Object ‘System.Windows.Forms.Label’
$timer1 = New-Object ‘System.Windows.Forms.Timer’
$InitialFormWindowState = New-Object ‘System.Windows.Forms.FormWindowState’
$form1_Load = {
$TotalTime = 5 #in seconds
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
#Start the timer
$timer1.Start()
}
$timer1_Tick={
#Use Get-Date for Time Accuracy
[TimeSpan]$span = $script:StartTime – (Get-Date)
#Update the display
if ($span.TotalSeconds -le 0) {
$timer1.Stop()
$form1.Close()
}
}
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$form1.remove_Load($form1_Load)
$timer1.remove_Tick($timer1_Tick)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
$form1.SuspendLayout()
#
# form1
#
$form1.ControlBox = $false
$form1.StartPosition = “CenterScreen”
$form1.text = “BitLocker Installation”
$form1.Size = New-Object System.Drawing.Size(300,100)
$form1.Font = “Segoe UI,12”
$form1.Topmost = $True
$form1.ForeColor = [System.Drawing.Color]::White
$form1.BackColor = [System.Drawing.Color]::LightSteelBlue
$form1.add_Load($form1_Load)
#
# label1
#
$label1.Text = “Checking System…”
$label1.AutoSize = $True
$label1.Font = “Segoe UI,18”
$label1.Location = “42,15”
$form1.Controls.Add($label1)
#
# timer1
#
$timer1.add_Tick($timer1_Tick)
$form1.ResumeLayout()
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
}
#display form
Splash1| Out-Null
PS – Not my own work, I amended a script I found on the web, I just can’t remember where I found it. If I find the link I’ll post it here. Credit where credit’s due after all…
Advertisements