Skip to content

Instantly share code, notes, and snippets.

@t-mat
Created April 8, 2024 08:53
Show Gist options
  • Save t-mat/1e3561abd5fef60698a50111b7a44d04 to your computer and use it in GitHub Desktop.
Save t-mat/1e3561abd5fef60698a50111b7a44d04 to your computer and use it in GitHub Desktop.
[Unity][Windows] Select a file in the file explorer
using System;
using System.IO;
using System.Runtime.InteropServices;
using UnityEditor;
using UnityEngine;
internal static class Test {
[MenuItem("Help/Test/SHOpenFolderAndSelectItems")]
private static void MenuItem_MyMenu_SHOpenFolderAndSelectItems() {
string path = "C:/Windows/system.ini";
string fullPath = Path.GetFullPath(path);
SelectInFileExplorer(fullPath);
Debug.Log($"fullPath={fullPath}");
}
private static void SelectInFileExplorer(string fullPath) {
try {
IntPtr pidl = Shell32Methods.ILCreateFromPathW(fullPath);
try {
int errorCode = Shell32Methods.SHOpenFolderAndSelectItems(pidl, 0, IntPtr.Zero, 0);
Debug.Log($"errorCode={errorCode}");
}
finally {
Shell32Methods.ILFree(pidl);
}
}
catch {
// do nothing
}
}
private static class Shell32Methods {
// https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-ilfree
[DllImport("shell32.dll")]
public static extern void ILFree(IntPtr pidl);
// https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-ilcreatefrompathw
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr ILCreateFromPathW(string pszPath);
// https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shopenfolderandselectitems
[DllImport("shell32.dll")]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidl, uint cild, IntPtr apidl, uint dwFlags);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment