功能介绍:
打开Windows文件夹浏览器,返回选择的文件夹路径。
备注:
- 打开的浏览器文件夹始终置于最顶层。
- visibleInBackground要设置为true。
效果如下:
代码如下:
using System;
using System.Runtime.InteropServices;
namespace Folder
{
public class PathBrowser
{
// 浏览对话框中包含一个编辑框,在该编辑框中用户可以输入选中项的名字。
const int BIF_EDITBOX = 0x00000010;
// 新用户界面
const int BIF_NEWDIALOGSTYLE = 0x00000040;
const int BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX);
const int MAX_PATH_LENGTH = 2048;
public static string FolderBrowserDlg(string defaultPath = "")
{
OpenDlgDir dlg = new OpenDlgDir();
dlg.pszDisplayName = defaultPath;
dlg.ulFlags = BIF_USENEWUI;
//设置hwndOwner==0时,是非模态对话框,设置hwndOwner!=0时为模态对话框
dlg.hwndOwner = DllOpenFileDialog.GetForegroundWindow();
IntPtr pidlPtr = DllOpenFileDialog.SHBrowseForFolder(dlg);
char[] charArray = new char[MAX_PATH_LENGTH];
DllOpenFileDialog.SHGetPathFromIDList(pidlPtr, charArray);
string foldPath = new String(charArray);
foldPath = foldPath.Substring(0, foldPath.IndexOf('\0'));
return foldPath;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenDlgDir
{
public IntPtr hwndOwner = IntPtr.Zero;
public IntPtr pidlRoot = IntPtr.Zero;
public String pszDisplayName = null;
public String lpszTitle = null;
public UInt32 ulFlags = 0;
public IntPtr lpfn = IntPtr.Zero;
public IntPtr lParam = IntPtr.Zero;
public int iImage = 0;
}
public class DllOpenFileDialog
{
[DllImport("shell32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern IntPtr SHBrowseForFolder([In, Out] OpenDlgDir odd);
[DllImport("shell32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern bool SHGetPathFromIDList([In] IntPtr pidl, [In, Out] char[] fileName);
/// <summary>
/// 获取当前窗口句柄
/// </summary>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
}
}
来源:CSDN
作者:Unity小码农
链接:https://blog.csdn.net/qq_33808037/article/details/103763396