PowerScript:System.Windows.Forms.FolderBrowserDialog 在后台打开

PowerScript: System.Windows.Forms.FolderBrowserDialog opening in the background

这里是 PowerScript 菜鸟。

我找到了一段代码,它允许用户通过文件夹浏览器对话框 select 一个文件夹,而不是手动输入文件夹的路径。

按预期工作,除了文件夹浏览器对话框经常在屏幕上的其他 windows 后面打开,这让人厌烦。

代码如下:

Function Get-Folder($initialDirectory)

{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

    $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
    $foldername.Description = "Select a folder"
    $foldername.rootfolder = "MyComputer"
    $foldername.SelectedPath = $initialDirectory

    if($foldername.ShowDialog() -eq "OK")
    {
        $folder += $foldername.SelectedPath
    }
    return $folder
}

$FolderNavn = Get-Folder($StartFolder)

如何让文件夹浏览器对话框打开 'on top of' 所有其他 Windows?

谢谢。

要将 BrowseForFolder 对话框设置为 TopMost,您需要使用 ShowDialog() 重载方法和一个指定对话框所有者(父)表单的参数。

我认为最简单的方法是创建一个新表单,将 属性 Topmost 设置为 $true 并将其用作所有者表单:

function Get-Folder {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
        [string]$Message = "Please select a directory.",

        [Parameter(Mandatory=$false, Position=1)]
        [string]$InitialDirectory,

        [Parameter(Mandatory=$false)]
        [System.Environment+SpecialFolder]$RootFolder = [System.Environment+SpecialFolder]::Desktop,

        [switch]$ShowNewFolderButton
    )
    Add-Type -AssemblyName System.Windows.Forms
    $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
    $dialog.Description  = $Message
    $dialog.SelectedPath = $InitialDirectory
    $dialog.RootFolder   = $RootFolder
    $dialog.ShowNewFolderButton = if ($ShowNewFolderButton) { $true } else { $false }
    $selected = $null

    # force the dialog TopMost
    # Since the owning window will not be used after the dialog has been 
    # closed we can just create a new form on the fly within the method call
    $result = $dialog.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
    if ($result -eq [Windows.Forms.DialogResult]::OK){
        $selected = $dialog.SelectedPath
    }
    # clear the FolderBrowserDialog from memory
    $dialog.Dispose()
    # return the selected folder
    $selected
}