Call OpenFileDialog from PowerShell

When I run the following, PowerShell waits for the dialog to complete, even if the dialog never appears:

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowDialog( ) 

Calling ShowDialog on Windows.Forms.Form works fine. I also tried to create a Form and pass it as the parent of $d.ShowDialog , but the result did not change.

+6
powershell winforms
source share
3 answers

I was able to duplicate your problem and found a workaround. I do not know why this is happening, but it happened to others.

If you set the ShowHelp property to $ true, you get the dialog to display correctly.

Example:

 [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowHelp = $true $d.ShowDialog( ) 

Good luck

+17
source share

It seems to me that the dialog really opens just fine, but it is located behind the powershell console window. Unfortunately, it does not appear in the taskbar, so there is no indication that it is there unless you have moved the powershell or Alt + Tab window. It also seems that the ShowHelp workaround had no effect for me.

EDIT . Here you can do this using the idea of ​​a secondary form. The main idea is to create a new form that opens the OpenFileDialog from within the Shown event. The key activates the form before opening the dialog so that the form appears on the front panel and a dialog box appears. I moved the form overs by setting an off-screen value for the location, but you can also set Form.Visible = $ false from within the Shown event.

 [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $ofn = New-Object System.Windows.Forms.OpenFileDialog $outer = New-Object System.Windows.Forms.Form $outer.StartPosition = [Windows.Forms.FormStartPosition] "Manual" $outer.Location = New-Object System.Drawing.Point -100, -100 $outer.Size = New-Object System.Drawing.Size 10, 10 $outer.add_Shown( { $outer.Activate(); $ofn.ShowDialog( $outer ); $outer.Close(); } ) $outer.ShowDialog() 
+2
source share

Apparently, this has something to do with the Multi-Threaded Apartment (MTA) mode. It seems to work fine in Single-Threaded Apartment (-STA) mode.

See also: Could you explain STA and MTA?

+1
source share

All Articles