0

I am trying to put a time limit for an input box before which it closes.

I have used the if command and end-date such that:

$endDate = (Get-Date).AddSeconds(10)
while ((Get-Date) -lt $endDate) { 


[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"



$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
{$Choice = $objTextBox.SelectedItem.ToString(); $objForm.Close()}})




$objForm.Topmost = $True

if ((Get-Date) -ge $Fate) { $objForm.Invoke( }


$objForm.Add_Shown({$objForm.Activate()})
 [void] $objForm.ShowDialog()
}

if ((Get-Date) -ge $endDate) { #whatever Function Here}

it seems that the input box stops all the actions of the script. I have tried to time the second function (the one starting with if) inside the same function without using the while loop but it didn't work.

Any Ideas?

1
  • This code looks broken in multiple ways, and your question is hard to read and understand. Commented Mar 17, 2014 at 19:35

1 Answer 1

1

Even if the input box stops actions of the script, it may not block event subscriptions from running. If that's the case, you could use the System.Timers.Timer class to register a timeout.

If you create the following event registration just before you invoke the input box, it may allow you to close the input box.

$Timer = New-Object -TypeName System.Timers.Timer;
$Timer.Interval = 30000; # Timeout in milliseconds (30 seconds)

$Action = {
    Start-Sleep -Seconds 10; # Create a delay for the action
    $objForm.Close(); # This line *should* close the Form object
    $Timer.Enabled = $false; # Stop the timer from executing
    Get-EventSubscriber -SourceIdentifier Timer | Unregister-Event; # Unregister the event handler
    };

Register-ObjectEvent -InputObject $Timer -EventName Elapsed -SourceIdentifier Timer -Action $Action;
$Timer.Enabled = $true;
Sign up to request clarification or add additional context in comments.

2 Comments

the code works well, thank you. but I don't want $Action to start at time 0. I couldn't manage to fix it. In addition, I want to remove the objectevent after the execution of the code.
I've updated the answer to include a delay for the action (virtually causing a 40 second instead of 30 second delay), and also added a line that unregisters the event subscription.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.