Moss
Moss

Reputation: 335

BrowseForFolder-Dialog: center and make TopMost

I have a Winforms Gui with a BrowseForFolder-Dialog.

Is there any way to make this dialog the TopMost window and/or center it on the screen?

$getfolder = New-Object -com shell.application
$foldername = $getfolder.BrowseForFolder(0,"Text",16,"")

Upvotes: 4

Views: 2574

Answers (2)

t1meless
t1meless

Reputation: 539

You have to specify the owner handle.

$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle
$getfolder = New-Object -ComObject Shell.Application
$foldername = $getfolder.BrowseForFolder([int]$handle, "Text", 16, "")

But it is a mixture of COM and .NET. I recommend the following solution

$win32WindowDefinition = @"
using System;
using System.Windows.Forms;

public class Win32Window : IWin32Window
{
    public Win32Window(IntPtr handle)
    {
        Handle = handle;
    }

    public IntPtr Handle { get; private set; }
}
"@

Add-Type -TypeDefinition $win32WindowDefinition -ReferencedAssemblies System.Windows.Forms.dll 

$ownerHandle = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
$folderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialogResult = $folderBrowserDialog.ShowDialog($ownerHandle)
if ($dialogResult -eq [System.Windows.Forms.DialogResult]::OK) {
    $folderName = $folderBrowserDialog.SelectedPath
}

from http://poshcode.org/2002

Upvotes: 2

Reza Aghaei
Reza Aghaei

Reputation: 125207

If you can use FolderBrowserDialog, to show it as top-most and at the center of screen, it's enough to pass a TopMost form to its ShowDialog method.

C# Example

var f = new FolderBrowserDialog();
f.ShowDialog(new Form() { TopMost = true}); 
this.Activate();

Powershell Example

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$folder = New-Object System.Windows.Forms.FolderBrowserDialog
$form = New-Object System.Windows.Forms.Form -property @{TopMost = $True}
$folder.ShowDialog($form)

Upvotes: 2

Related Questions