diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23dd698..249e181 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,13 @@
## Unreleased
+## 1.0.0-beta.1.3.2
+
+- Classic shortcuts now work with games that start through a loader (a small `.exe` that creates the real game, e.g. `main.bin`, and exits). VNAR stays in the background while the game runs and gives the game's windows the shortcut's AppUserModelID, relaunch command, name and icon, so the game groups with its pinned shortcut instead of showing a second taskbar button, and the running game can be pinned (it pins a VNAR shortcut, not the loader's `.bin`).
+- Classic launches of games that run as administrator (marked in VNAR, `requireAdministrator`/`highestAvailable` in the executable's manifest, or Windows' "Run as administrator" compatibility setting) start an elevated VNAR first, so it can set the identity on the game's elevated windows. There is still a single UAC prompt: the elevated VNAR starts Locale Emulator, which does not ask again. The elevated copy receives the data folder and the shortcut's icon as arguments, so it also works when UAC runs it as another user. Cancelling UAC cancels the launch, as before.
+- Games started from the library window (Play or double-click) go through the same path in a separate VNAR process: their windows get the game's AppUserModelID, so they group with a pinned classic shortcut instead of showing a second button, and they are marked as not pinnable, so pinning a running game can no longer pin its executable without Locale Emulator. Pinning stays a deliberate choice made with a classic shortcut. Administrator games get the same single-UAC elevation, and the launch keeps being watched if the library window is closed.
+- `VNAR.ShellTests` checks that a window owned by another process in the game folder receives that identity (pinnable for shortcut launches, not pinnable for library launches), and that windows from other folders are left alone. `VNAR.CoreTests` covers which games are treated as running as administrator.
+
## 1.0.0-beta.1.3.1
- Fix classic (`.lnk`) shortcuts for games whose executable, folder or name has Japanese (or other non-ANSI) characters. They were written through `WScript.Shell`, which turned those characters into `?`, so the icon pointed to a file that does not exist and Windows showed VNAR's icon instead of the game's, making the shortcut look like a modern one. Classic shortcuts are now written with the Unicode Shell Link API. Shortcuts created with Beta 1.3 for those games need to be created again.
diff --git a/Directory.Build.props b/Directory.Build.props
index 7c286ef..57d486b 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -7,7 +7,7 @@
GitHub release tag all derive from this value.
-->
- 1.0.0-beta.1.3.1
+ 1.0.0-beta.1.3.2
false
diff --git a/LocaleGameHub/App.xaml.cs b/LocaleGameHub/App.xaml.cs
index 005680f..c851eff 100644
--- a/LocaleGameHub/App.xaml.cs
+++ b/LocaleGameHub/App.xaml.cs
@@ -1,6 +1,7 @@
using System.Text;
using System.Windows;
using System.Windows.Threading;
+using LocaleGameHub.Models;
using LocaleGameHub.Services;
namespace LocaleGameHub;
@@ -16,6 +17,17 @@ protected override void OnStartup(StartupEventArgs e)
try
{
+ // An elevated copy started for a classic launch gets the data folder of the
+ // VNAR that started it (UAC may run it as another user). This must happen
+ // before anything reads AppDataPaths.
+ var isElevatedRelaunch = false;
+ var dataDir = ElevationService.GetArgument(e.Args, ElevationService.DataDirArgument);
+ if (!string.IsNullOrWhiteSpace(dataDir) && Directory.Exists(dataDir))
+ {
+ Environment.SetEnvironmentVariable(AppDataPaths.DataDirOverrideVariable, dataDir);
+ isElevatedRelaunch = true;
+ }
+
var launch = ParseLaunchRequest(e.Args, out var gameId);
var isGameLaunch = launch != LaunchRequest.None;
@@ -50,7 +62,37 @@ protected override void OnStartup(StartupEventArgs e)
if (isGameLaunch)
{
- LaunchFromShortcut(preferences, gameId);
+ var game = FindGame(preferences, gameId);
+ if (launch == LaunchRequest.Classic)
+ {
+ var fromLibrary = ElevationService.HasFlag(e.Args, ElevationService.FromLibraryArgument);
+ var relaunchIcon = ElevationService.GetArgument(e.Args, ElevationService.RelaunchIconArgument)
+ ?? GameWindowIdentityService.ResolveRelaunchIcon(game);
+
+ // A game that runs as administrator needs an elevated VNAR to set
+ // its windows' identity. Hand the launch to an elevated copy: the
+ // user still gets a single UAC prompt (instead of Locale Emulator's).
+ if (!isElevatedRelaunch && !ElevationService.IsCurrentProcessElevated() &&
+ ElevationService.GameRunsElevated(game))
+ {
+ var result = ElevationService.RelaunchElevated(ShortcutService.ResolveVnarExecutable(), game.Id, relaunchIcon, fromLibrary);
+ if (result != ElevationService.RelaunchResult.Failed)
+ {
+ Shutdown(0); // started, or the user said no to UAC
+ return;
+ }
+ // Elevation is not available: launch as before.
+ }
+
+ // The library window already recorded the launch.
+ LaunchGame(preferences, game, recordLaunch: !fromLibrary);
+ // Stay in the background while the game runs, giving its windows
+ // the shortcut's identity (see GameWindowIdentityService).
+ WatchGameWindows(game, relaunchIcon, preventPinning: fromLibrary);
+ return;
+ }
+
+ LaunchGame(preferences, game);
Shutdown(0);
return;
}
@@ -99,7 +141,7 @@ private static LaunchRequest ParseLaunchRequest(string[] args, out Guid gameId)
return LaunchRequest.None;
}
- private static void LaunchFromShortcut(LibraryService library, Guid gameId)
+ private static GameEntry FindGame(LibraryService library, Guid gameId)
{
var game = library.Games.FirstOrDefault(g => g.Id == gameId);
if (game is null)
@@ -114,13 +156,50 @@ private static void LaunchFromShortcut(LibraryService library, Guid gameId)
throw new InvalidOperationException(message);
}
+ return game;
+ }
+
+ private static void LaunchGame(LibraryService library, GameEntry game, bool recordLaunch = true)
+ {
var locale = new LocaleEmulatorService(library);
locale.Launch(game);
+ if (!recordLaunch) return;
// Re-reads the library under the shared lock so edits made meanwhile in the
// library window are not overwritten by this process's startup snapshot.
library.RecordLaunch(game.Id, DateTime.UtcNow);
}
+ private void WatchGameWindows(GameEntry game, string relaunchIcon, bool preventPinning)
+ {
+ var thread = new Thread(() =>
+ {
+ try
+ {
+ var watcher = new GameWindowIdentityService(
+ game,
+ ShortcutService.ResolveVnarExecutable(),
+ relaunchIcon,
+ preventPinning);
+ watcher.Watch();
+ }
+ catch (Exception ex)
+ {
+ // The game is already running; only the taskbar grouping is lost.
+ WriteCrashLog("GameWindowIdentity", ex);
+ }
+ finally
+ {
+ Dispatcher.BeginInvoke(new Action(() => Shutdown(0)));
+ }
+ })
+ {
+ IsBackground = true,
+ Name = "VNAR game window identity"
+ };
+ thread.SetApartmentState(ApartmentState.STA);
+ thread.Start();
+ }
+
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
WriteCrashLog("DispatcherUnhandledException", e.Exception);
diff --git a/LocaleGameHub/MainWindow.xaml.cs b/LocaleGameHub/MainWindow.xaml.cs
index ccffeb2..e45cdf1 100644
--- a/LocaleGameHub/MainWindow.xaml.cs
+++ b/LocaleGameHub/MainWindow.xaml.cs
@@ -665,7 +665,13 @@ private void LaunchGame(GameEntry game)
{
try
{
- _locale.Launch(game);
+ // Validate here (missing LEProc opens Settings below), then hand the launch
+ // to a separate VNAR process, like a classic shortcut: it gives the game's
+ // windows their identity so they group with a pinned shortcut, and it keeps
+ // working if this window is closed while playing.
+ var start = _locale.BuildStartInfo(game);
+ if (!TryLaunchThroughVnar(game))
+ System.Diagnostics.Process.Start(start);
game.LastPlayedUtc = DateTime.UtcNow;
_library.SaveGames();
}
@@ -691,6 +697,25 @@ private void LaunchGame(GameEntry game)
}
}
+ private static bool TryLaunchThroughVnar(GameEntry game)
+ {
+ try
+ {
+ var vnarExe = ShortcutService.ResolveVnarExecutable();
+ using var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(
+ vnarExe, $"--launch {game.Id:D} {ElevationService.FromLibraryArgument}")
+ {
+ UseShellExecute = false,
+ WorkingDirectory = Path.GetDirectoryName(vnarExe) ?? AppContext.BaseDirectory
+ });
+ return process is not null;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
private void GameCard_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
if (sender is not FrameworkElement { Tag: GameEntry game } card) return;
diff --git a/LocaleGameHub/Services/ElevationRules.cs b/LocaleGameHub/Services/ElevationRules.cs
new file mode 100644
index 0000000..9989221
--- /dev/null
+++ b/LocaleGameHub/Services/ElevationRules.cs
@@ -0,0 +1,60 @@
+using System.Text.RegularExpressions;
+
+namespace LocaleGameHub.Services;
+
+///
+/// Decides whether a game will run as administrator. Pure logic, so it can be tested
+/// on any OS; gathers the inputs on Windows.
+///
+public static class ElevationRules
+{
+ public const string RequireAdministrator = "requireAdministrator";
+ public const string HighestAvailable = "highestAvailable";
+ public const string AsInvoker = "asInvoker";
+
+ private static readonly Regex LevelPattern = new(
+ "requestedExecutionLevel[^>]*?\\blevel\\s*=\\s*[\"']([A-Za-z]+)[\"']",
+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+
+ /// The requestedExecutionLevel of an application manifest, or null if it has none.
+ public static string? ManifestLevel(string? manifestXml)
+ {
+ if (string.IsNullOrWhiteSpace(manifestXml)) return null;
+ var match = LevelPattern.Match(manifestXml);
+ if (!match.Success) return null;
+
+ var level = match.Groups[1].Value;
+ foreach (var known in new[] { RequireAdministrator, HighestAvailable, AsInvoker })
+ if (level.Equals(known, StringComparison.OrdinalIgnoreCase)) return known;
+ return null;
+ }
+
+ ///
+ /// Reads Windows' compatibility layers for an executable (the "Run this program as
+ /// an administrator" checkbox stores RUNASADMIN; RUNASHIGHEST also exists).
+ /// Returns the matching manifest-style level, or null.
+ ///
+ public static string? CompatibilityLevel(string? layers)
+ {
+ if (string.IsNullOrWhiteSpace(layers)) return null;
+ var flags = layers.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ if (flags.Any(f => f.Equals("RUNASADMIN", StringComparison.OrdinalIgnoreCase))) return RequireAdministrator;
+ if (flags.Any(f => f.Equals("RUNASHIGHEST", StringComparison.OrdinalIgnoreCase))) return HighestAvailable;
+ return null;
+ }
+
+ /// The game uses VNAR's administrator Locale Emulator profile.
+ /// From the exe's manifest (see ).
+ /// From Windows' compatibility settings (see ).
+ ///
+ /// The user is an administrator running with a filtered token: "highestAvailable"
+ /// elevates for them, while for a standard user it runs as invoker.
+ ///
+ public static bool GameRunsElevated(bool markedAdmin, string? manifestLevel, string? compatibilityLevel, bool userCanElevateSilently)
+ {
+ if (markedAdmin) return true;
+ if (manifestLevel == RequireAdministrator || compatibilityLevel == RequireAdministrator) return true;
+ if (manifestLevel == HighestAvailable || compatibilityLevel == HighestAvailable) return userCanElevateSilently;
+ return false;
+ }
+}
diff --git a/LocaleGameHub/Services/ElevationService.cs b/LocaleGameHub/Services/ElevationService.cs
new file mode 100644
index 0000000..34bb883
--- /dev/null
+++ b/LocaleGameHub/Services/ElevationService.cs
@@ -0,0 +1,202 @@
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Text;
+using LocaleGameHub.Models;
+using Microsoft.Win32;
+
+namespace LocaleGameHub.Services;
+
+///
+/// Classic launches of games that run as administrator: VNAR must be elevated too,
+/// or Windows will not let it give the game's windows the shortcut's identity.
+/// The shortcut's VNAR relaunches itself elevated and that copy starts Locale
+/// Emulator, so the user still sees a single UAC prompt (Locale Emulator does not
+/// ask again when started from an elevated process).
+///
+public static class ElevationService
+{
+ /// VNAR's data folder, passed to the elevated copy: elevation may run as another user.
+ public const string DataDirArgument = "--data-dir";
+
+ /// The icon of the shortcut that was used, which the elevated copy cannot see.
+ public const string RelaunchIconArgument = "--relaunch-icon";
+
+ /// The launch came from the library window, not from a shortcut.
+ public const string FromLibraryArgument = "--from-library";
+
+ private const int ErrorCancelled = 1223;
+
+ public static bool GameRunsElevated(GameEntry game)
+ {
+ string? manifest = null;
+ string? layers = null;
+ try { manifest = ReadManifest(game.ExePath); } catch { /* unreadable exe: rely on the rest */ }
+ try { layers = ReadCompatibilityLayers(game.ExePath); } catch { }
+
+ return ElevationRules.GameRunsElevated(
+ game.RunAsAdmin,
+ ElevationRules.ManifestLevel(manifest),
+ ElevationRules.CompatibilityLevel(layers),
+ IsFilteredAdministrator());
+ }
+
+ public enum RelaunchResult { Started, Cancelled, Failed }
+
+ /// Starts an elevated VNAR for the same classic launch.
+ public static RelaunchResult RelaunchElevated(string vnarExe, Guid gameId, string relaunchIcon, bool fromLibrary)
+ {
+ var args = new StringBuilder()
+ .Append("--launch ").Append(gameId.ToString("D"))
+ .Append(' ').Append(DataDirArgument).Append(' ').Append(QuoteArgument(AppDataPaths.Root))
+ .Append(' ').Append(RelaunchIconArgument).Append(' ').Append(QuoteArgument(relaunchIcon))
+ .Append(fromLibrary ? " " + FromLibraryArgument : string.Empty)
+ .ToString();
+ try
+ {
+ using var process = Process.Start(new ProcessStartInfo(vnarExe, args)
+ {
+ UseShellExecute = true,
+ Verb = "runas",
+ WorkingDirectory = Path.GetDirectoryName(vnarExe) ?? AppContext.BaseDirectory
+ });
+ return process is null ? RelaunchResult.Failed : RelaunchResult.Started;
+ }
+ catch (Win32Exception ex) when (ex.NativeErrorCode == ErrorCancelled)
+ {
+ return RelaunchResult.Cancelled;
+ }
+ catch
+ {
+ return RelaunchResult.Failed;
+ }
+ }
+
+ public static bool HasFlag(string[] args, string name)
+ => args.Any(a => a.Equals(name, StringComparison.OrdinalIgnoreCase));
+
+ /// Value of "--name value" in the command line, or null.
+ public static string? GetArgument(string[] args, string name)
+ {
+ for (var i = 0; i + 1 < args.Length; i++)
+ if (args[i].Equals(name, StringComparison.OrdinalIgnoreCase))
+ return args[i + 1];
+ return null;
+ }
+
+ // Windows command-line quoting (CommandLineToArgvW rules), so a path ending in
+ // a backslash or containing quotes reaches the elevated copy unchanged.
+ private static string QuoteArgument(string value)
+ {
+ var sb = new StringBuilder("\"");
+ var backslashes = 0;
+ foreach (var c in value)
+ {
+ if (c == '\\') { backslashes++; continue; }
+ sb.Append('\\', c == '"' ? backslashes * 2 + 1 : backslashes);
+ backslashes = 0;
+ sb.Append(c);
+ }
+ sb.Append('\\', backslashes * 2).Append('"');
+ return sb.ToString();
+ }
+
+ // ------------------------------------------------------------------ token
+
+ public static bool IsCurrentProcessElevated()
+ {
+ using var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
+ return TryGetTokenInt(identity.Token, TokenElevation, out var elevated) && elevated != 0;
+ }
+
+ /// An administrator whose current token is the filtered (UAC) one.
+ private static bool IsFilteredAdministrator()
+ {
+ using var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
+ return TryGetTokenInt(identity.Token, TokenElevationTypeClass, out var type) && type == TokenElevationTypeLimited;
+ }
+
+ private const int TokenElevationTypeClass = 18;
+ private const int TokenElevation = 20;
+ private const int TokenElevationTypeLimited = 3;
+
+ private static bool TryGetTokenInt(IntPtr token, int infoClass, out int value)
+ {
+ var buffer = Marshal.AllocHGlobal(sizeof(int));
+ try
+ {
+ var ok = GetTokenInformation(token, infoClass, buffer, sizeof(int), out _);
+ value = ok ? Marshal.ReadInt32(buffer) : 0;
+ return ok;
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
+ }
+
+ // --------------------------------------------------------------- manifest
+
+ private const uint LoadLibraryAsDatafile = 0x2;
+ private const uint LoadLibraryAsImageResource = 0x20;
+ private static readonly IntPtr RtManifest = new(24);
+ private static readonly IntPtr ProcessManifestId = new(1);
+
+ private static string? ReadManifest(string exePath)
+ {
+ if (!File.Exists(exePath)) return null;
+ var module = LoadLibraryExW(exePath, IntPtr.Zero, LoadLibraryAsDatafile | LoadLibraryAsImageResource);
+ if (module == IntPtr.Zero) return null;
+ try
+ {
+ var resource = FindResourceW(module, ProcessManifestId, RtManifest);
+ if (resource == IntPtr.Zero) return null;
+ var size = SizeofResource(module, resource);
+ var loaded = LoadResource(module, resource);
+ var data = loaded == IntPtr.Zero ? IntPtr.Zero : LockResource(loaded);
+ if (data == IntPtr.Zero || size == 0) return null;
+
+ var bytes = new byte[size];
+ Marshal.Copy(data, bytes, 0, (int)size);
+ return Encoding.UTF8.GetString(bytes);
+ }
+ finally
+ {
+ FreeLibrary(module);
+ }
+ }
+
+ private const string LayersKey = @"Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers";
+
+ private static string? ReadCompatibilityLayers(string exePath)
+ {
+ var path = Path.GetFullPath(exePath);
+ using var user = Registry.CurrentUser.OpenSubKey(LayersKey);
+ using var machine = Registry.LocalMachine.OpenSubKey(LayersKey);
+ var values = new[] { user?.GetValue(path) as string, machine?.GetValue(path) as string }
+ .Where(v => !string.IsNullOrWhiteSpace(v));
+ var joined = string.Join(' ', values);
+ return joined.Length == 0 ? null : joined;
+ }
+
+ [DllImport("advapi32.dll", SetLastError = true)]
+ private static extern bool GetTokenInformation(IntPtr token, int infoClass, IntPtr info, int length, out int returned);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern IntPtr LoadLibraryExW(string fileName, IntPtr file, uint flags);
+
+ [DllImport("kernel32.dll")]
+ private static extern bool FreeLibrary(IntPtr module);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ private static extern IntPtr FindResourceW(IntPtr module, IntPtr name, IntPtr type);
+
+ [DllImport("kernel32.dll")]
+ private static extern uint SizeofResource(IntPtr module, IntPtr resource);
+
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr LoadResource(IntPtr module, IntPtr resource);
+
+ [DllImport("kernel32.dll")]
+ private static extern IntPtr LockResource(IntPtr resource);
+}
diff --git a/LocaleGameHub/Services/GameWindowIdentityService.cs b/LocaleGameHub/Services/GameWindowIdentityService.cs
new file mode 100644
index 0000000..39a4078
--- /dev/null
+++ b/LocaleGameHub/Services/GameWindowIdentityService.cs
@@ -0,0 +1,425 @@
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Text;
+using LocaleGameHub.Models;
+
+namespace LocaleGameHub.Services;
+
+///
+/// Gives the game's windows the identity of the classic shortcut that launched it.
+///
+/// A classic .lnk carries the game's AppUserModelID, but Windows only passes it on
+/// as long as every process in the chain cooperates. Some games start through a
+/// tiny loader that creates the real game (e.g. "main.bin") with an empty
+/// STARTUPINFO and exits; the game window then has no link to the shortcut, so
+/// Windows shows a second taskbar button next to the pinned one and cannot pin the
+/// running game (it does not know how to relaunch a ".bin").
+///
+/// After a classic launch, VNAR watches for visible top-level windows of processes
+/// whose executable lives in the game's folder and sets on each one the game's
+/// AppUserModelID plus a relaunch command ("VNAR.exe --launch <id>"), name and
+/// icon. The windows then group with the pinned shortcut, and pinning the running
+/// game pins a VNAR shortcut. Windows of elevated games cannot be changed from a
+/// non-elevated VNAR; those are skipped.
+///
+public sealed class GameWindowIdentityService
+{
+ // PKEY_AppUserModel_* share this format ID.
+ private static readonly Guid AppUserModelFormat = new("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3");
+ public const uint AppIdPropertyId = 5;
+ public const uint RelaunchCommandPropertyId = 2;
+ public const uint RelaunchIconPropertyId = 3;
+ public const uint RelaunchNamePropertyId = 4;
+ public const uint PreventPinningPropertyId = 9;
+ private static Guid PropertyStoreIid = new("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99");
+
+ /// How long to wait for the first game window (loaders, config dialogs, slow starts).
+ public static readonly TimeSpan FirstWindowTimeout = TimeSpan.FromMinutes(3);
+
+ /// Keep watching this long after the last game process ended (a launcher handing over to the game).
+ private static readonly TimeSpan ExitGrace = TimeSpan.FromSeconds(15);
+
+ private readonly string _gameFolder;
+ private readonly string _vnarExe;
+ private readonly int _ownProcessId = Environment.ProcessId;
+ private readonly Dictionary _isGameProcess = new();
+ private readonly HashSet _gameProcesses = new();
+ private readonly HashSet _handled = new();
+
+ ///
+ /// Launches from the library window: the game still groups with a pinned classic
+ /// shortcut, but cannot be pinned from its own taskbar button. Pinning stays a
+ /// deliberate choice made by creating a classic shortcut, and nothing pinned this
+ /// way can point at the game's executable without Locale Emulator.
+ ///
+ public GameWindowIdentityService(GameEntry game, string vnarExe, string relaunchIcon, bool preventPinning = false)
+ {
+ var folder = Path.GetDirectoryName(Path.GetFullPath(game.ExePath))
+ ?? throw new InvalidOperationException("The game executable has no folder.");
+ _gameFolder = Path.EndsInDirectorySeparator(folder) ? folder : folder + Path.DirectorySeparatorChar;
+ _vnarExe = Path.GetFullPath(vnarExe);
+
+ AppId = TaskbarIdentityService.GetGameAppId(game.Id);
+ RelaunchCommand = $"\"{_vnarExe}\" --launch {game.Id:D}";
+ RelaunchIcon = relaunchIcon;
+ DisplayName = game.Name;
+ PreventPinning = preventPinning;
+ }
+
+ public string AppId { get; }
+ public string RelaunchCommand { get; }
+ public string RelaunchIcon { get; }
+ public string DisplayName { get; }
+ public bool PreventPinning { get; }
+
+ ///
+ /// Watches until the game has closed (or no game window appeared in time).
+ /// Run it on an STA thread.
+ ///
+ public void Watch()
+ {
+ var clock = Stopwatch.StartNew();
+ TimeSpan? lastAlive = null;
+ while (true)
+ {
+ TagNewWindows();
+ if (AnyGameProcessAlive()) lastAlive = clock.Elapsed;
+
+ if (lastAlive is null)
+ {
+ if (clock.Elapsed > FirstWindowTimeout) return;
+ }
+ else if (clock.Elapsed - lastAlive.Value > ExitGrace)
+ {
+ return;
+ }
+
+ // Poll quickly until the game shows up, then just catch windows it
+ // creates later (e.g. when switching to full screen).
+ Thread.Sleep(lastAlive is null ? 250 : 1000);
+ }
+ }
+
+ /// Sets the identity on game windows not handled yet. Returns how many were changed.
+ public int TagNewWindows()
+ {
+ var windows = new List<(IntPtr Handle, int ProcessId)>();
+ EnumWindows((hwnd, _) =>
+ {
+ if (IsWindowVisible(hwnd))
+ {
+ GetWindowThreadProcessId(hwnd, out var pid);
+ windows.Add((hwnd, (int)pid));
+ }
+ return true;
+ }, IntPtr.Zero);
+
+ // Forget closed windows and processes without windows, so a reused handle
+ // or process ID is looked at again.
+ _handled.RemoveWhere(h => !IsWindow(h));
+ var seen = windows.Select(w => w.ProcessId).ToHashSet();
+ foreach (var pid in _isGameProcess.Keys.Where(p => !seen.Contains(p)).ToList())
+ _isGameProcess.Remove(pid);
+
+ var changed = 0;
+ foreach (var (hwnd, pid) in windows)
+ {
+ if (!IsGameProcess(pid)) continue;
+ _gameProcesses.Add(pid);
+ if (!_handled.Add(hwnd)) continue;
+
+ // A failure (usually an elevated game) is not retried for that window.
+ if (TryApply(hwnd)) changed++;
+ }
+ return changed;
+ }
+
+ private bool IsGameProcess(int pid)
+ {
+ if (pid == _ownProcessId || pid == 0) return false;
+ if (_isGameProcess.TryGetValue(pid, out var known)) return known;
+
+ var path = TryGetProcessPath(pid);
+ var isGame = path is not null &&
+ path.StartsWith(_gameFolder, StringComparison.OrdinalIgnoreCase) &&
+ !string.Equals(path, _vnarExe, StringComparison.OrdinalIgnoreCase);
+ _isGameProcess[pid] = isGame;
+ return isGame;
+ }
+
+ private bool AnyGameProcessAlive()
+ {
+ _gameProcesses.RemoveWhere(pid => !IsProcessRunning(pid));
+ return _gameProcesses.Count > 0;
+ }
+
+ private bool TryApply(IntPtr hwnd)
+ {
+ try
+ {
+ if (PreventPinning) ApplyUnpinnable(hwnd, AppId);
+ else ApplyToWindow(hwnd, AppId, RelaunchCommand, RelaunchIcon, DisplayName);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// Sets the relaunch properties first and the AppUserModelID last: changing the
+ /// ID is what makes the taskbar regroup the window and read the rest.
+ ///
+ public static void ApplyToWindow(IntPtr hwnd, string appId, string relaunchCommand, string relaunchIcon, string displayName)
+ {
+ Marshal.ThrowExceptionForHR(SHGetPropertyStoreForWindow(hwnd, ref PropertyStoreIid, out var store));
+ try
+ {
+ SetString(store, RelaunchCommandPropertyId, relaunchCommand);
+ SetString(store, RelaunchIconPropertyId, relaunchIcon);
+ SetString(store, RelaunchNamePropertyId, displayName);
+ SetString(store, AppIdPropertyId, appId);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// The game's AppUserModelID, marked as not pinnable (PreventPinning must be set before the ID).
+ public static void ApplyUnpinnable(IntPtr hwnd, string appId)
+ {
+ Marshal.ThrowExceptionForHR(SHGetPropertyStoreForWindow(hwnd, ref PropertyStoreIid, out var store));
+ try
+ {
+ var key = new TaskbarIdentityService.PropertyKey { FormatId = AppUserModelFormat, PropertyId = PreventPinningPropertyId };
+ var value = new TaskbarIdentityService.PropVariant { ValueType = 11, BoolValue = -1 }; // VT_BOOL, VARIANT_TRUE
+ Marshal.ThrowExceptionForHR(store.SetValue(ref key, ref value));
+ SetString(store, AppIdPropertyId, appId);
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// Reads PKEY_AppUserModel_PreventPinning (used by the shell tests).
+ public static bool ReadWindowPreventPinning(IntPtr hwnd)
+ {
+ Marshal.ThrowExceptionForHR(SHGetPropertyStoreForWindow(hwnd, ref PropertyStoreIid, out var store));
+ try
+ {
+ var key = new TaskbarIdentityService.PropertyKey { FormatId = AppUserModelFormat, PropertyId = PreventPinningPropertyId };
+ Marshal.ThrowExceptionForHR(store.GetValue(ref key, out var value));
+ try { return value.ValueType == 11 && value.BoolValue != 0; }
+ finally { PropVariantClear(ref value); }
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ /// Reads one of the window's AppUserModel strings (used by the shell tests).
+ public static string? ReadWindowString(IntPtr hwnd, uint propertyId)
+ {
+ Marshal.ThrowExceptionForHR(SHGetPropertyStoreForWindow(hwnd, ref PropertyStoreIid, out var store));
+ try
+ {
+ var key = new TaskbarIdentityService.PropertyKey { FormatId = AppUserModelFormat, PropertyId = propertyId };
+ Marshal.ThrowExceptionForHR(store.GetValue(ref key, out var value));
+ try
+ {
+ return value.ValueType == 31 ? Marshal.PtrToStringUni(value.StringValue) : null;
+ }
+ finally
+ {
+ PropVariantClear(ref value);
+ }
+ }
+ finally
+ {
+ Marshal.ReleaseComObject(store);
+ }
+ }
+
+ private static void SetString(TaskbarIdentityService.IPropertyStore store, uint propertyId, string text)
+ {
+ var key = new TaskbarIdentityService.PropertyKey { FormatId = AppUserModelFormat, PropertyId = propertyId };
+ var value = new TaskbarIdentityService.PropVariant
+ {
+ ValueType = 31, // VT_LPWSTR
+ StringValue = Marshal.StringToCoTaskMemUni(text)
+ };
+ try
+ {
+ Marshal.ThrowExceptionForHR(store.SetValue(ref key, ref value));
+ }
+ finally
+ {
+ Marshal.FreeCoTaskMem(value.StringValue);
+ }
+ }
+
+ // ------------------------------------------------------------- relaunch icon
+
+ ///
+ /// The icon to show for the running game and for a shortcut pinned from it:
+ /// the icon of the .lnk that started VNAR (Windows passes its path in
+ /// STARTUPINFO), else the game's executable, else VNAR's generic icon.
+ ///
+ public static string ResolveRelaunchIcon(GameEntry game)
+ {
+ var fromLink = TryReadLaunchingLinkIcon();
+ if (fromLink is not null) return fromLink;
+
+ if (File.Exists(game.ExePath) && ExtractIconEx(game.ExePath, -1, null, null, 0) > 0)
+ return game.ExePath + ",0";
+
+ return ShortcutService.GetGenericIconPath() + ",0";
+ }
+
+ private static string? TryReadLaunchingLinkIcon()
+ {
+ try
+ {
+ var info = new StartupInfo { Size = Marshal.SizeOf() };
+ GetStartupInfoW(ref info);
+ if ((info.Flags & StartfTitleIsLinkName) == 0 || info.Title == IntPtr.Zero) return null;
+
+ var linkPath = Marshal.PtrToStringUni(info.Title);
+ if (string.IsNullOrWhiteSpace(linkPath) || !File.Exists(linkPath)) return null;
+
+ var link = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("00021401-0000-0000-C000-000000000046"), true)!)!;
+ try
+ {
+ ((System.Runtime.InteropServices.ComTypes.IPersistFile)link).Load(linkPath, 0);
+ var buffer = new StringBuilder(1024);
+ if (((IShellLinkWIcon)link).GetIconLocation(buffer, buffer.Capacity, out var index) != 0) return null;
+ var iconPath = Environment.ExpandEnvironmentVariables(buffer.ToString());
+ return File.Exists(iconPath) ? $"{iconPath},{index}" : null;
+ }
+ finally
+ {
+ Marshal.FinalReleaseComObject(link);
+ }
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ // ------------------------------------------------------------------ interop
+
+ private const int StartfTitleIsLinkName = 0x800;
+ private const uint ProcessQueryLimitedInformation = 0x1000;
+ private const uint StillActive = 259;
+
+ private static string? TryGetProcessPath(int pid)
+ {
+ var handle = OpenProcess(ProcessQueryLimitedInformation, false, (uint)pid);
+ if (handle == IntPtr.Zero) return null;
+ try
+ {
+ var buffer = new StringBuilder(32768);
+ var size = buffer.Capacity;
+ return QueryFullProcessImageNameW(handle, 0, buffer, ref size) ? buffer.ToString(0, size) : null;
+ }
+ finally
+ {
+ CloseHandle(handle);
+ }
+ }
+
+ private static bool IsProcessRunning(int pid)
+ {
+ var handle = OpenProcess(ProcessQueryLimitedInformation, false, (uint)pid);
+ if (handle == IntPtr.Zero) return false;
+ try
+ {
+ return GetExitCodeProcess(handle, out var code) && code == StillActive;
+ }
+ finally
+ {
+ CloseHandle(handle);
+ }
+ }
+
+ private delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
+
+ [DllImport("user32.dll")]
+ private static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam);
+
+ [DllImport("user32.dll")]
+ private static extern bool IsWindowVisible(IntPtr hwnd);
+
+ [DllImport("user32.dll")]
+ private static extern bool IsWindow(IntPtr hwnd);
+
+ [DllImport("user32.dll")]
+ private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern IntPtr OpenProcess(uint access, bool inheritHandle, uint processId);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern bool QueryFullProcessImageNameW(IntPtr process, uint flags, StringBuilder exeName, ref int size);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
+
+ [DllImport("kernel32.dll")]
+ private static extern bool CloseHandle(IntPtr handle);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ private static extern void GetStartupInfoW(ref StartupInfo info);
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ private static extern uint ExtractIconEx(string file, int index, IntPtr[]? large, IntPtr[]? small, uint icons);
+
+ [DllImport("shell32.dll")]
+ private static extern int SHGetPropertyStoreForWindow(
+ IntPtr hwnd, ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out TaskbarIdentityService.IPropertyStore store);
+
+ [DllImport("ole32.dll")]
+ private static extern int PropVariantClear(ref TaskbarIdentityService.PropVariant value);
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct StartupInfo
+ {
+ public int Size;
+ public IntPtr Reserved;
+ public IntPtr Desktop;
+ public IntPtr Title;
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute;
+ public int Flags;
+ public short ShowWindow;
+ public short Reserved2;
+ public IntPtr Reserved2Pointer;
+ public IntPtr StdInput, StdOutput, StdError;
+ }
+
+ // Vtable order of IShellLinkW up to GetIconLocation; only that getter is used.
+ [ComImport]
+ [Guid("000214F9-0000-0000-C000-000000000046")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellLinkWIcon
+ {
+ [PreserveSig] int GetPath(IntPtr file, int maxPath, IntPtr findData, uint flags);
+ [PreserveSig] int GetIDList(out IntPtr idList);
+ [PreserveSig] int SetIDList(IntPtr idList);
+ [PreserveSig] int GetDescription(IntPtr name, int maxName);
+ [PreserveSig] int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string name);
+ [PreserveSig] int GetWorkingDirectory(IntPtr dir, int maxPath);
+ [PreserveSig] int SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string dir);
+ [PreserveSig] int GetArguments(IntPtr args, int maxPath);
+ [PreserveSig] int SetArguments([MarshalAs(UnmanagedType.LPWStr)] string args);
+ [PreserveSig] int GetHotkey(out short hotkey);
+ [PreserveSig] int SetHotkey(short hotkey);
+ [PreserveSig] int GetShowCmd(out int showCmd);
+ [PreserveSig] int SetShowCmd(int showCmd);
+ [PreserveSig] int GetIconLocation([MarshalAs(UnmanagedType.LPWStr)] StringBuilder iconPath, int maxIconPath, out int iconIndex);
+ }
+}
diff --git a/LocaleGameHub/Services/LocaleEmulatorService.cs b/LocaleGameHub/Services/LocaleEmulatorService.cs
index 16bdfbb..7271547 100644
--- a/LocaleGameHub/Services/LocaleEmulatorService.cs
+++ b/LocaleGameHub/Services/LocaleEmulatorService.cs
@@ -73,7 +73,14 @@ public void AutoAssignJapaneseProfiles()
_library.SaveSettings();
}
- public void Launch(GameEntry game)
+ public void Launch(GameEntry game) => Process.Start(BuildStartInfo(game));
+
+ ///
+ /// Checks everything a launch needs (game exe, LEProc, profile) and returns how to
+ /// start it. The library window calls this first so setup errors still show there
+ /// even though the launch itself runs in a separate VNAR process.
+ ///
+ public ProcessStartInfo BuildStartInfo(GameEntry game)
{
if (!File.Exists(game.ExePath))
throw new FileNotFoundException(LocalizationService.Bi("No se encontró el ejecutable del juego.", "The game executable was not found."), game.ExePath);
@@ -104,15 +111,13 @@ public void Launch(GameEntry game)
if (!string.IsNullOrWhiteSpace(game.Arguments))
args += " " + game.Arguments.Trim();
- var psi = new ProcessStartInfo
+ return new ProcessStartInfo
{
FileName = leProc,
Arguments = args,
WorkingDirectory = Path.GetDirectoryName(game.ExePath) ?? Environment.CurrentDirectory,
UseShellExecute = true
};
-
- Process.Start(psi);
}
private static string Quote(string value) => $"\"{value.Replace("\"", "\\\"")}\"";
diff --git a/LocaleGameHub/Services/TaskbarIdentityService.cs b/LocaleGameHub/Services/TaskbarIdentityService.cs
index f4b6e49..88bcaa0 100644
--- a/LocaleGameHub/Services/TaskbarIdentityService.cs
+++ b/LocaleGameHub/Services/TaskbarIdentityService.cs
@@ -66,7 +66,7 @@ public static void SetShortcutIdentity(string shortcutPath, Guid gameId)
private static extern int SetCurrentProcessExplicitAppUserModelID(string appId);
[StructLayout(LayoutKind.Sequential, Pack = 4)]
- private struct PropertyKey
+ internal struct PropertyKey
{
public Guid FormatId;
public uint PropertyId;
@@ -75,24 +75,25 @@ private struct PropertyKey
// PROPVARIANT's union contains a counted pointer: 16 bytes on x86,
// 24 on x64. Include that member so the native layout is correct on both.
[StructLayout(LayoutKind.Sequential)]
- private struct CountedPointer
+ internal struct CountedPointer
{
public uint Count;
public IntPtr Pointer;
}
[StructLayout(LayoutKind.Explicit)]
- private struct PropVariant
+ internal struct PropVariant
{
[FieldOffset(0)] public ushort ValueType;
[FieldOffset(8)] public IntPtr StringValue;
+ [FieldOffset(8)] public short BoolValue;
[FieldOffset(8)] public CountedPointer ArrayValue;
}
[ComImport]
[Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
- private interface IPropertyStore
+ internal interface IPropertyStore
{
[PreserveSig] int GetCount(out uint count);
[PreserveSig] int GetAt(uint index, out PropertyKey key);
diff --git a/README.es.md b/README.es.md
index d79645d..f17cb90 100644
--- a/README.es.md
+++ b/README.es.md
@@ -7,7 +7,7 @@
Un launcher ligero para Windows enfocado en visual novels, con integración con Locale Emulator, metadatos de VNDB, edición de portadas, navegación por desarrolladores, favoritos, soporte WebP y accesos directos inteligentes.
-[English](README.md) · [Descargar Beta 1.3.1](https://github.com/JAVCIF/vnar/releases/tag/v1.0.0-beta.1.3.1)
+[English](README.md) · [Descargar Beta 1.3.2](https://github.com/JAVCIF/vnar/releases/tag/v1.0.0-beta.1.3.2)
## Descargas
@@ -16,8 +16,8 @@ Un launcher ligero para Windows enfocado en visual novels, con integración con
| Paquete | Descripción | Descarga |
| --- | --- | --- |
-| Instalador | Instalación autocontenida, acceso en el menú Inicio y acceso de escritorio opcional | [VNAR-Setup.exe](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.1/VNAR-Setup.exe) |
-| Portable | Versión autocontenida; descomprime y ejecuta `VNAR.exe` | [VNAR-Portable-win-x64.zip](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.1/VNAR-Portable-win-x64.zip) |
+| Instalador | Instalación autocontenida, acceso en el menú Inicio y acceso de escritorio opcional | [VNAR-Setup.exe](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.2/VNAR-Setup.exe) |
+| Portable | Versión autocontenida; descomprime y ejecuta `VNAR.exe` | [VNAR-Portable-win-x64.zip](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.2/VNAR-Portable-win-x64.zip) |
Locale Emulator **no viene incluido** dentro de VNAR. En el primer arranque puedes seleccionar un `LEProc.exe` existente o dejar que VNAR descargue la versión oficial de Locale Emulator.
@@ -95,6 +95,20 @@ apuntan al ejecutable del launcher. Los accesos anteriores siguen funcionando;
recréalos como Modernos para obtener el comportamiento nuevo. La opción de
administrador sigue cambiando únicamente el perfil de Locale Emulator.
+Mientras un juego abierto desde un acceso Clásico está en marcha, VNAR se queda en
+segundo plano y le da a las ventanas del juego la identidad del acceso. Así el juego
+se agrupa con su acceso anclado, y anclar el juego abierto ancla un acceso de VNAR
+(con Locale Emulator) en vez del ejecutable del juego. Esto también cubre los juegos
+que arrancan con un pequeño lanzador que crea el juego real (por ejemplo `main.bin`)
+y se cierra. Con los juegos que se ejecutan como administrador (marcados en VNAR,
+exigidos por el propio ejecutable o configurados en las opciones de compatibilidad de
+Windows), el VNAR del acceso se eleva primero, así que sigue habiendo una sola
+ventana de UAC.
+
+Los juegos abiertos desde la biblioteca también se agrupan con su acceso Clásico
+anclado, pero no se pueden anclar desde el juego abierto: para anclar un juego, crea
+un acceso Clásico. Así nada anclado apunta al ejecutable del juego sin Locale Emulator.
+
Los iconos de accesos modernos se guardan en la carpeta de datos de VNAR, por lo que
los personalizados y el genérico sobreviven si mueves una instalación portable. Al
abrir VNAR normalmente desde la ubicación nueva, se actualiza el registro por usuario
@@ -102,7 +116,7 @@ del protocolo `vnar://`.
## Estado del proyecto
-Versión pública actual: **Beta 1.3.1 (`1.0.0-beta.1.3.1`)**.
+Versión pública actual: **Beta 1.3.2 (`1.0.0-beta.1.3.2`)**.
Puedes usar GitHub Issues para reportar errores o proponer mejoras.
diff --git a/README.md b/README.md
index 89d1b03..1e684a3 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
A lightweight Windows launcher for visual novels with Locale Emulator integration, VNDB metadata, cover editing, developer browsing, favorites, WebP support, and smart desktop shortcuts.
-[Español](README.es.md) · [Download Beta 1.3.1](https://github.com/JAVCIF/vnar/releases/tag/v1.0.0-beta.1.3.1)
+[Español](README.es.md) · [Download Beta 1.3.2](https://github.com/JAVCIF/vnar/releases/tag/v1.0.0-beta.1.3.2)
## Downloads
@@ -16,8 +16,8 @@ A lightweight Windows launcher for visual novels with Locale Emulator integratio
| Package | Description | Download |
| --- | --- | --- |
-| Installer | Self-contained installation with Start Menu integration and optional desktop shortcut | [VNAR-Setup.exe](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.1/VNAR-Setup.exe) |
-| Portable | Self-contained portable build; extract and run `VNAR.exe` | [VNAR-Portable-win-x64.zip](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.1/VNAR-Portable-win-x64.zip) |
+| Installer | Self-contained installation with Start Menu integration and optional desktop shortcut | [VNAR-Setup.exe](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.2/VNAR-Setup.exe) |
+| Portable | Self-contained portable build; extract and run `VNAR.exe` | [VNAR-Portable-win-x64.zip](https://github.com/JAVCIF/vnar/releases/download/v1.0.0-beta.1.3.2/VNAR-Portable-win-x64.zip) |
Locale Emulator is **not bundled** with VNAR. On first launch, VNAR can use an existing `LEProc.exe` or download the official Locale Emulator release for you.
@@ -101,6 +101,19 @@ the launcher executable. Existing shortcuts keep working; recreate them as Moder
to receive the new behavior. The administrator option still only selects the Locale
Emulator profile.
+While a game opened from a Classic shortcut is running, VNAR stays in the background
+and gives the game's windows the shortcut's identity. The game then groups with its
+pinned shortcut, and pinning the running game pins a VNAR shortcut (with Locale
+Emulator) instead of the game's executable. This also covers games that start
+through a small loader that creates the real game (for example `main.bin`) and exits.
+For games that run as administrator (marked in VNAR, required by the executable, or
+set in Windows' compatibility options), the shortcut's VNAR elevates itself first, so
+there is still a single UAC prompt.
+
+Games started from the library window group with their pinned Classic shortcut too,
+but cannot be pinned from the running game: create a Classic shortcut to pin a game.
+This way a pin never points at a game's executable without Locale Emulator.
+
Modern shortcut icons are stored in VNAR's data folder so custom icons and the
generic VNAR icon survive moving a portable installation. If the portable folder is
moved, VNAR refreshes its per-user `vnar://` registration on the next normal start.
@@ -113,7 +126,7 @@ dotnet run --project .\tests\VNAR.ShellTests\VNAR.ShellTests.csproj -c Release
## Project status
-Current public build: **Beta 1.3.1 (`1.0.0-beta.1.3.1`)**.
+Current public build: **Beta 1.3.2 (`1.0.0-beta.1.3.2`)**.
Bug reports and suggestions are welcome through GitHub Issues.
diff --git a/tests/VNAR.CoreTests/Program.cs b/tests/VNAR.CoreTests/Program.cs
index 8cfc2ed..b1f17a7 100644
--- a/tests/VNAR.CoreTests/Program.cs
+++ b/tests/VNAR.CoreTests/Program.cs
@@ -44,6 +44,7 @@ private static async Task Main(string[] args)
Section("Scanner: results, progress and cancellation", Scanner);
await SectionAsync("Downloads: size limits and no partial files", Downloads);
Section("Links: vnar:// parsing", VnarLinks);
+ Section("Elevation: which games run as administrator", ElevationDecisions);
Section("Version: single source in Directory.Build.props", Version);
if (OperatingSystem.IsWindows())
Section("DPAPI: real Windows encryption round trip", Dpapi);
@@ -488,6 +489,28 @@ private static async Task Throws(Func action)
// ------------------------------------------------------------ links/version
+ private static void ElevationDecisions()
+ {
+ Check(ElevationRules.ManifestLevel("") == ElevationRules.RequireAdministrator,
+ "manifest requireAdministrator");
+ Check(ElevationRules.ManifestLevel("") == ElevationRules.HighestAvailable,
+ "manifest highestAvailable (any attribute order and case)");
+ Check(ElevationRules.ManifestLevel("") == ElevationRules.AsInvoker, "manifest asInvoker");
+ Check(ElevationRules.ManifestLevel(null) is null && ElevationRules.ManifestLevel("") is null, "no manifest or no level");
+
+ Check(ElevationRules.CompatibilityLevel("~ RUNASADMIN HIGHDPIAWARE") == ElevationRules.RequireAdministrator, "compatibility RUNASADMIN");
+ Check(ElevationRules.CompatibilityLevel("~ runashighest") == ElevationRules.HighestAvailable, "compatibility RUNASHIGHEST");
+ Check(ElevationRules.CompatibilityLevel("~ WIN7RTM") is null && ElevationRules.CompatibilityLevel(null) is null, "other compatibility flags");
+
+ Check(ElevationRules.GameRunsElevated(true, null, null, false), "marked as administrator in VNAR");
+ Check(!ElevationRules.GameRunsElevated(false, ElevationRules.AsInvoker, null, true), "normal game");
+ Check(ElevationRules.GameRunsElevated(false, ElevationRules.RequireAdministrator, null, false), "exe requires administrator");
+ Check(ElevationRules.GameRunsElevated(false, null, ElevationRules.RequireAdministrator, false), "\"run as administrator\" compatibility setting");
+ Check(ElevationRules.GameRunsElevated(false, ElevationRules.HighestAvailable, null, true) &&
+ !ElevationRules.GameRunsElevated(false, ElevationRules.HighestAvailable, null, false),
+ "highestAvailable elevates only for administrators");
+ }
+
private static void VnarLinks()
{
var id = Guid.Parse("64f78cd1-0b00-4271-a9e1-89abc55f66cc");
diff --git a/tests/VNAR.CoreTests/VNAR.CoreTests.csproj b/tests/VNAR.CoreTests/VNAR.CoreTests.csproj
index 58a6437..5397618 100644
--- a/tests/VNAR.CoreTests/VNAR.CoreTests.csproj
+++ b/tests/VNAR.CoreTests/VNAR.CoreTests.csproj
@@ -1,7 +1,7 @@