using System.Runtime.InteropServices;
namespace Titano.Setup.Interop;
/// Win32 entry points used by setup (shell notification, delayed delete, process image path).
internal static partial class NativeMethods
{
public const int ERROR_CANCELLED = 1223;
public const int HRESULT_ERROR_CANCELLED = unchecked((int)0x800704C7);
private const int SHCNE_ASSOCCHANGED = 0x08000000;
private const int SHCNF_IDLIST = 0x0000;
private const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
/// Tells Explorer that file associations changed so icons and "open with" refresh.
public static void NotifyAssociationsChanged() => SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
/// Asks Windows to delete a file or empty folder at the next restart (needs administrator rights).
public static bool DeleteAtReboot(string path) => MoveFileExW(path, null, MOVEFILE_DELAY_UNTIL_REBOOT);
/// Full path of the executable of process , or null when it cannot be queried.
public static unsafe string? ProcessImagePath(int processId)
{
var handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId);
if (handle == IntPtr.Zero) return null;
try
{
const int capacity = 1024;
var buffer = stackalloc char[capacity];
var length = capacity;
return QueryFullProcessImageNameW(handle, 0, buffer, ref length) ? new string(buffer, 0, length) : null;
}
finally
{
CloseHandle(handle);
}
}
[LibraryImport("shell32.dll")]
private static partial void SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool MoveFileExW(string existingFileName, string? newFileName, int flags);
[LibraryImport("kernel32.dll", SetLastError = true)]
private static partial IntPtr OpenProcess(int desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, int processId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static unsafe partial bool QueryFullProcessImageNameW(IntPtr process, int flags, char* exeName, ref int size);
[LibraryImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseHandle(IntPtr handle);
}