Powershell form close form after 30 minutes if no activity exists

To close a PowerShell form after 30 minutes of inactivity, you can use a timer to track user activity and close the form if no interaction occurs within the specified time. Below is an example script using Windows Forms:
# Load Windows Forms assembly Add-Type -AssemblyName System.Windows.Forms # Create the form $form = New-Object System.Windows.Forms.Form $form.Text = "Auto-Close Form" $form.Size = New-Object System.Drawing.Size(300, 200) # Create a label $label = New-Object System.Windows.Forms.Label $label.Text = "This form will close after 30 minutes of inactivity." $label.AutoSize = $true $label.Location = New-Object System.Drawing.Point(10, 10) $form.Controls.Add($label) # Timer to track inactivity $timer = New-Object System.Windows.Forms.Timer $timer.Interval = 1000 # 1 second $inactivityLimit = 30 * 60 # 30 minutes in seconds $inactivityCounter = 0 # Reset inactivity counter on user interaction $form.Add_MouseMove({ $inactivityCounter = 0 }) $form.Add_KeyPress({ $inactivityCounter = 0 }) # Timer tick event $timer.Add_Tick({ $inactivityCounter++ if ($inactivityCounter -ge $inactivityLimit) { $timer.Stop() $form.Close() } }) # Start the timer and show the form $timer.Start() $form.ShowDialog() # Dispose resources $form.Dispose() $timer.Dispose()
Explanation:
- Form Creation: A simple form with a label is created.
- Timer: A
System.Windows.Forms.Timer
is used to track inactivity in seconds. - User Interaction: Mouse movement (
MouseMove
) and key presses (KeyPress
) reset the inactivity counter. - Auto-Close: If the counter reaches 30 minutes (1800 seconds), the form closes automatically.
This script ensures the form closes after 30 minutes of inactivity while resetting the timer upon user interaction