BrowseForFolder-Dialog:center并制作TopMost

时间:2016-04-21 12:35:02

标签: c# winforms powershell

我有Winforms Gui BrowseForFolder-Dialog

有没有办法让这个对话框在屏幕上显示 TopMost 窗口和/或中心

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

2 个答案:

答案 0 :(得分:2)

您必须指定所有者句柄。

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

但它是COM和.NET的混合体。我推荐以下解决方案

$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
}

来自http://poshcode.org/2002

答案 1 :(得分:1)

如果您可以使用FolderBrowserDialog,将其显示为最顶层且位于屏幕中心,则可以将TopMost表单传递给其ShowDialog方法

C#示例

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

Powershell示例

[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)