OpenFileItem.cs: win32api所需结构体StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)
不可少,指定非托管对象必须
using System; using System.Runtime.InteropServices; namespace Assets.Editor.rayfalling { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class OpenFileItem { public int structSize = 0; public IntPtr dlgOwner = IntPtr.Zero; public IntPtr instance = IntPtr.Zero; public String filter = null; public String customFilter = null; public int maxCustFilter = 0; public int filterIndex = 0; public String file = null; public int maxFile = 0; public String fileTitle = null; public int maxFileTitle = 0; public String initialDir = null; public String title = null; public int flags = 0; public short fileOffset = 0; public short fileExtension = 0; public String defExt = null; public IntPtr custData = IntPtr.Zero; public IntPtr hook = IntPtr.Zero; public String templateName = null; public IntPtr reservedPtr = IntPtr.Zero; public int reservedInt = 0; public int flagsEx = 0; } }
OpenFileDialog.cs: 调用系统dll
using System.Runtime.InteropServices; namespace Assets.Editor.rayfalling { public class OpenFileDialog { //链接指定系统函数 打开文件对话框 [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)] public static extern bool GetOpenFileName([In, Out] OpenFileItem ofn); //链接指定系统函数 另存为对话框 [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)] public static extern bool GetSaveFileName([In, Out] OpenFileItem ofn); } }
测试代码:
using System.Runtime.InteropServices; using Assets.Editor.rayfalling; using UnityEditor; using UnityEngine; using OpenFileDialog = Assets.Editor.rayfalling.OpenFileDialog; namespace Assets.Editor { public class ExternalDownload : MonoBehaviour { [UnityEditor.MenuItem("External Download/Import")] static void Import() { var openFileName = new OpenFileItem(); openFileName.structSize = Marshal.SizeOf(openFileName); openFileName.filter = "unitypackage(*.unitypackage)\0*.*|\0*.*"; openFileName.file = new string(new char[256]); openFileName.maxFile = openFileName.file.Length; openFileName.fileTitle = new string(new char[64]); openFileName.maxFileTitle = openFileName.fileTitle.Length; openFileName.initialDir = UnityEngine.Application.streamingAssetsPath.Replace('/', '\\'); //默认路径 openFileName.title = "请选择路径或者文件"; openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008; if (!OpenFileDialog.GetSaveFileName(openFileName)) return; var fileName = openFileName.file; AssetDatabase.ImportPackage(packagePath: fileName, false); } } }
参考来源: 简书
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
凤曦的小窝
本文地址: Windows下Unity 调用系统文件对话框
本文地址: Windows下Unity 调用系统文件对话框