最近需要做一个服务器一键开启客户端相同路径程序的功能,需要在服务器选择相应文件夹的程序,然后同时服务器客户度同时开启选中程序,首先需要从unity打开外部文件夹并选择文件的功能,具体操作如下:
首先创建一个单独的类,用来储存打开的系统窗口的设置,下面的变量没有特殊要求不需要做任何改动:
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
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;
}
然后我们需要在创建一个类导入Window的链接库,代码也不需要做更改:
using System.Runtime.InteropServices;
public class LocalDialog
{
//链接指定系统函数 打开文件对话框
[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
public static bool GetOFN([In, Out] OpenFileName ofn)
{
return GetOpenFileName(ofn);//执行打开文件的操作
}
//链接指定系统函数 另存为对话框
[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
public static extern bool GetSaveFileName([In, Out] OpenFileName ofn);
public static bool GetSFN([In, Out] OpenFileName ofn)
{
return GetSaveFileName(ofn);//执行保存选中文件的操作
}
}
完成上面两步就可以开始调用打开系统窗口选择文件的操作,我创建了一个类用来执行打开选择的方法,其中的打开文件夹方法如下:
public void OpenDirectory(string type)
{
openFileName = new OpenFileName();
openFileName.structSize = Marshal.SizeOf(openFileName);
openFileName.filter = "文件(*." + type + ")\0*." + type + "";
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 = Application.streamingAssetsPath.Replace('/', '\\');//默认路径
openFileName.title = "选择文件";
openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
if (LocalDialog.GetSaveFileName(openFileName))//点击系统对话框框保存按钮
{
//TODO
}
在这个方法里面要注意:对openFileName这个类里面的变量赋值就是设置系统窗口的效果,其中可以更改的地方有:
openFileName.title :表示打开的系统窗口名称
openFileName.filter:这个表示需要选择的文件类型,书写格式就是上面的格式,类型按照需求填写,打开的窗口效果如下:
我填写的类型是exe,可以选择的类型就是exe文件,
openFileName.filter = "文件(*." + type + ")\0*." + type + ""; \后面的意思就是剔除其他非exe文件,例如我后面有一个选择图片的功能,格式就是:openFileName.filter = "文件(*.png;*.jpg)\0*.png;*.jpg";表示选择png和jpg格式的文件,其他格式文件不在窗口显示,多种格式的文件选择加;隔开。效果如下:
到了这一步就可以进行打开外部文件夹选择文件了,当我们点击保存按钮就会执行红框里面的方法,就可以按照需求编写功能
欢迎加群:4364930讨论。