Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a form displayed by PowerShell sometimes not show up?

When I create a form (window) in PowerShell, I can usually display the form using .ShowDialog():

$form = New-Object System.Windows.Forms.Form
$form.ShowDialog()

.Visible is set to False before and after .ShowDialog().

But when I do a .Show() nothing is displayed on the screen:

$form.Show()

And .Visible is now set to True (presumably because .Show() made the form officially visible.)

When I now try to .ShowDialog() the form again, I get the following error message:

"Form that is already visible cannot be displayed as a modal dialog box. Set the form's visible property to false before calling showDialog."

But when I follow the instructions to .ShowDialog() again

$form.Visible=0
$form.ShowDialog()

the result is that nothing is displayed on the screen and PowerShell hangs and cannot recover (ctrl-c doesn't seem to work). I assume this is because the form is being displayed modally somewhere where I cannot see it (or tab to it). But why?

The coordinates of the form haven't changed. So how does the form decide when it is physically visible and when it isn't?

like image 559
Andrew J. Brehm Avatar asked Jan 22 '23 15:01

Andrew J. Brehm


2 Answers

Avoid using Show() from PowerShell as it requires a message pump and that isn't something the PowerShell console provides on the thread that creates your form. ShowDialog() works because the OS does the message pumping during this modal call. Creating the form and calling ShowDialog() works reliably for me.

like image 150
Keith Hill Avatar answered Jan 25 '23 23:01

Keith Hill


My problem: When using ShowDialog() as part of a powershell logon script, the first form window would not show and powershell would seem to freeze up on logon. Symptoms were simular to the original post.

Solution I found: Instead of using $form.showDialog(), use:

[System.Windows.Forms.Application]::Run($form)

Works great for me now, and only the first form in the series needed the change. All my other forms that come up afterwards in the script still use showDialog.

like image 31
Josh Avatar answered Jan 25 '23 23:01

Josh