文件夹浏览对话框置顶显示

3
我有以下 PowerShell 函数,它可以很好地工作,但是窗口会在 PowerShell ISE 后台打开。
# Shows folder browser dialog box and sets to variable
function Get-FolderName() {
    Add-Type -AssemblyName System.Windows.Forms
    $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
        SelectedPath = 'C:\Temp\'
        ShowNewFolderButton = $false
        Description = "Select Staging Folder."
    }
    # If cancel is clicked the script will exit
    if ($FolderBrowser.ShowDialog() -eq "Cancel") {break}
    $FolderBrowser.SelectedPath
} #end function Get-FolderName

我看到OpenFileDialog类有一个.TopMost属性,但似乎无法转移到FolderBrowserDialog类。

我是否遗漏了什么?

3个回答

4
希望这能帮到您。
Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$FolderBrowser.Description = 'Select the folder containing the data'
$result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
if ($result -eq [Windows.Forms.DialogResult]::OK){
$FolderBrowser.SelectedPath
} else {
exit
}

//编辑评论

ShowDialog()方法有两个变体(重载)。

请参阅文档:http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx

在第二种变量中,您可以指定应该是对话框母窗口的窗口。

Topmost应该谨慎使用或根本不使用!如果多个窗口都是最上面的,则哪个是最上面的?;-)) 首先尝试将您的窗口设置为母窗口,然后OpenfileDialog/SaveFileDialog应始终显示在您的窗口上方:

$openFileDialog1.ShowDialog($form1)

如果这还不够,可以使用Topmost。

您的对话窗口继承自主窗口的属性。如果您的主窗口是最顶层的,则对话框也是最顶层的。

以下是设置对话框为Topmost的示例。

但是,在此示例中,使用了一个新的未绑定窗口,因此对话框是未绑定的。

$openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))

好的,我在搜索中确实找到了这种方法,但它似乎并不总是有效,并且似乎会阻止vscode在控制台中接受凭据调用后的按键输入。我希望在我提供的原始代码的属性列表中添加“TopMost = $true”,但它似乎不喜欢它,而且我不知道为什么如果它可以在你的代码中使用...? - jshizzle
很抱歉,@Jaapaap,您的编辑全部关于OpenFileDialog,而不是FolderBrowserDialog - Theo

1
一种可靠的方法是在函数中添加一段 C# 代码。通过这段代码,您可以获取实现 IWin32Window 接口的 Windows 句柄。在 ShowDialog 函数中使用该句柄将确保对话框显示在顶部。
Function Get-FolderName {   
    # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
    # This handle must implement System.Windows.Forms.IWin32Window
    # Create a wrapper class that implements IWin32Window.
    # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
    $code = @"
using System;
using System.Windows.Forms;

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

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

    if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
        Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
    }
    # Get the window handle from the current process
    # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
    # Or write like this:
    $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

    # Or use the the window handle from the desktop
    # $owner =  New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
    # Or write like this:
    # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

    $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
        SelectedPath = 'C:\Temp\'
        ShowNewFolderButton = $false
        Description = "Select Staging Folder."
    }
    # set the return value only if a selection was made
    $result = $null
    If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
        $result = $FolderBrowser.SelectedPath
    }
    # clear the dialog from memory
    $FolderBrowser.Dispose()

    return $result
}

Get-FolderName

你也可以选择使用像这样的Shell.Application对象:

# Show an Open Folder Dialog and return the directory selected by the user.
function Get-FolderName {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
        [string]$Message = "Select a directory.",

        [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

        [switch]$ShowNewFolderButton
    )

    $browserForFolderOptions = 0x00000041                                  # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
    if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 }  # BIF_NONEWFOLDERBUTTON

    $browser = New-Object -ComObject Shell.Application
    # To make the dialog topmost, you need to supply the Window handle of the current process
    [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

    # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
    $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

    $result = $null
    if ($folder) { 
        $result = $folder.Self.Path 
    } 

    # Release and remove the used Com object from memory
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()


    return $result
}

$folder = Get-FolderName
if ($folder) { Write-Host "You selected the directory: $folder" }
else { "You did not select a directory." }

嗨Theo,非常感谢您的帮助和提供这个代码。由于时间紧迫,我不得不把这个需求放在了后面,但我会在有机会时重新审视它。很抱歉回复晚了,但我很感激。 - jshizzle

1
我刚发现一种简单的方法来获取PowerShell的IWin32Window值,以便窗体可以是模态的。创建一个System.Windows.Forms.NativeWindow对象,并将PowerShell的句柄赋给它。
function Show-FolderBrowser 
{       
    Param ( [Parameter(Mandatory=1)][string]$Title,
            [Parameter(Mandatory=0)][string]$DefaultPath = $(Split-Path $psISE.CurrentFile.FullPath),
            [Parameter(Mandatory=0)][switch]$ShowNewFolderButton)

    $DefaultPath = UNCPath2Mapped -path $DefaultPath; 

    $FolderBrowser = new-object System.Windows.Forms.folderbrowserdialog;
    $FolderBrowser.Description = $Title;
    $FolderBrowser.ShowNewFolderButton = $ShowNewFolderButton;
    $FolderBrowser.SelectedPath = $DefaultPath;
    $out = $null;

    $caller = [System.Windows.Forms.NativeWindow]::new()
    $caller.AssignHandle([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

    if (($FolderBrowser.ShowDialog($caller)) -eq [System.Windows.Forms.DialogResult]::OK.value__)
    {
        $out = $FolderBrowser.SelectedPath;
    }

    #Cleanup Disposabe Objects
    Get-Variable -ErrorAction SilentlyContinue -Scope 0  | Where-Object {($_.Value -is [System.IDisposable]) -and ($_.Name -notmatch "PS\s*")} | ForEach-Object {$_.Value.Dispose(); $_ | Clear-Variable -ErrorAction SilentlyContinue -PassThru | Remove-Variable -ErrorAction SilentlyContinue -Force;}

    return $out;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接