System.Windows.Forms.OpenFileDialog always ontop

Hello All

when using the following code to present a browse for file dialog to a user, sometimes the windows will open behind another windows and therefore cannot be seen. I know I have seen a tip somewhere on how to prevent this from happening (i.e. method etc) but I cannot locate it at the moment. Does someone know how to make sure the windows always opens on top?

Thanks all

 

function Read-OpenFileDialog ( `
[string]$WindowTitle="Please select a file", [string]$InitialDirectory="C:\", `
[string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect=$false)
{
Add-Type -AssemblyName System.Windows.Forms
$openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$openFileDialog.Title = $WindowTitle
$openFileDialog.InitialDirectory = $InitialDirectory
$openFileDialog.Filter = $Filter
if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
$openFileDialog.ShowHelp = $true
$openFileDialog.ShowDialog() | out-null
if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
}
Parents
No Data
Reply
  • Hello EBrant, yes because you have ShowHelp set to true a different form is being drawn. If you change this to false you will see that the window actually looks different. This window will popup everytime it is created.

    So try the following code, I tested this on Windows 8 and Server 2008R2, both with PowerShell v3. I have also improved your function by including a param() block, fixed the incorrect bracket on the first line and removed the line break character, which you should (almost) never use:

    function Read-OpenFileDialog {
    param (
    [string]$WindowTitle="Please select a file",
    [string]$InitialDirectory="C:\",
    [string]$Filter = "All files (*.*)|*.*",
    [switch]$AllowMultiSelect=$false
    )
    Add-Type -AssemblyName System.Windows.Forms
    $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openFileDialog.Title = $WindowTitle
    $openFileDialog.InitialDirectory = $InitialDirectory
    $openFileDialog.Filter = $Filter
    if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
    $openFileDialog.ShowHelp = $false
    $openFileDialog.ShowDialog() | out-null
    if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
    }
Children