Unity-打开Windows文件夹浏览器

好久不见. 提交于 2020-01-29 03:26:23

功能介绍:

打开Windows文件夹浏览器,返回选择的文件夹路径。

备注:

  1. 打开的浏览器文件夹始终置于最顶层。
  2. 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();
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!