diff --git a/CLAUDE.md b/CLAUDE.md index bdd7d8d..f789d5f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,27 +37,33 @@ The app starts unelevated. It only asks for administrator rights when a symbolic ### Key Components -1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate. +1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate. With `--link-helper` it runs the hidden elevated helper instead (see "Administrator rights"). 2. **App.xaml / App.xaml.cs**: Loads MahApps.Metro styles and syncs the theme (light/dark and accent color) with Windows. 3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, and a footer with the About button, an inline error line and the Create link button. Styles live in `Window.Resources`. -4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop, and link creation (`CreateLink()` and `SendCommand()`, which runs `cmd.exe /c mklink`). -5. **MainWindow.Inputs.cs**: Field validation with inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, the up-front admin notice, and the administrator restart prompt. -6. **Elevation.cs**: `LaunchOptions` (command-line parsing and correctly quoted argument building) and `Elevation` (admin check, symbolic link privilege probe, elevated restart with `runas`, the UAC shield icon). +4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop, and link creation (`CreateLink()`, `SendCommand()`, the move-and-link flow, and `RunMklinkAsync()`). +5. **MainWindow.Inputs.cs**: Field validation with inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, the up-front admin notice, and starting the elevated helper on demand (`ElevateIfNeededAsync()`). +6. **Elevation.cs**: `LaunchOptions` (command-line parsing) and `Elevation` (admin check, symbolic link privilege probe, the UAC shield icon). +7. **LinkCommand.cs**: `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used by the window and by the elevated helper. +8. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe. +9. **LinkMover.cs**: File system helpers for moving an existing file or folder to the target before linking. ### Link Creation Flow 1. User picks folder or file mode (pills) and a link type. Junction is folder-only, hard link is file-only. 2. User fills in the link location, link name and target (typing, browsing, or drag and drop). 3. Create link (or Enter, it is the default button) runs `ValidateInputs()`, which marks bad fields inline. -4. `EnsureCanCreateLinkAsync()` checks whether a symbolic link can be created. If not, it offers to restart as administrator. -5. `CreateLink()` handles an existing item at the link path, then `SendCommand()` runs mklink and shows the result. +4. `RefreshSymlinkAccessNow()` probes again whether a symbolic link needs administrator rights. +5. `CreateLink()` handles an existing item at the link path (delete it, or move it to the target), then `SendCommand()` runs mklink and shows the result. `ElevateIfNeededAsync()` is called before the first change on disk. ### Administrator rights - Junctions and hard links never need admin. Symbolic links need admin unless Windows Developer Mode is on. - `Elevation.CanCreateSymbolicLinks()` probes by creating a throwaway symlink in the temp folder. -- The probe runs when the window loads (and again on activation while admin is needed). If symbolic links need admin, Create link shows the UAC shield and the footer shows a notice with a "Restart as administrator" link, so the user knows before filling in the form. Field errors take the same footer spot and hide the notice. -- When elevation is needed, the app restarts itself with `runas` and passes the form values as quoted arguments (`--mode`, `--type`, `--location`, `--name`, `--target`). The old `--engage` flag is still accepted and ignored. +- The probe runs when the window loads (again on activation while admin is needed, and on Create link). If symbolic links need admin, Create link shows the UAC shield and the footer says Windows will ask for permission, so the user knows before filling in the form. Field errors take the same footer spot and hide the notice. +- The window never restarts or elevates itself, so drag and drop keeps working. When a symbolic link needs admin, `ElevateIfNeededAsync()` starts `Symlinker.exe --link-helper ` with `runas` (one UAC prompt). The helper has no window: it connects back over the named pipe and creates each link it is sent with mklink. It stays up until the window closes (or it is ended, then the next symbolic link starts a new one), so the user approves UAC once per session. While it runs, the shield and the footer notice are hidden. Only symbolic links that need admin go through it; junctions and hard links always run unelevated. +- Elevation happens before anything on disk changes (deleting an existing item, or the move-and-link flow), so declining the UAC prompt (Win32 error 1223) quietly stops and leaves everything as it was. +- Both ends check the other's process ID on the pipe (`GetNamedPipeClientProcessId` / `GetNamedPipeServerProcessId`), and `LinkCommand` rejects paths with quotes or line breaks, so the helper only ever runs a single mklink. +- Command-line options (`--mode`, `--type`, `--location`, `--name`, `--target`) still prefill the form. The old `--engage` flag is still accepted and ignored. ### Important Patterns @@ -79,8 +85,11 @@ Symlinker/ │ ├── App.xaml(.cs) # Application, theme sync │ ├── MainWindow.xaml # UI and styles │ ├── MainWindow.xaml.cs # Core window logic and link creation -│ ├── MainWindow.Inputs.cs # Validation, inline errors, admin restart -│ ├── Elevation.cs # LaunchOptions and elevation helpers +│ ├── MainWindow.Inputs.cs # Validation, inline errors, admin notice +│ ├── Elevation.cs # LaunchOptions, symlink probe, UAC shield +│ ├── LinkCommand.cs # Runs mklink +│ ├── ElevatedLinker.cs # Elevated link helper over a named pipe +│ ├── LinkMover.cs # Move-and-link file system helpers │ ├── Program.cs # Entry point │ ├── Properties/ │ │ ├── Resources.resx # English strings @@ -106,7 +115,7 @@ Releases are automated via GitHub Actions: ## Known Limitations -- **Drag and drop**: Works in the normal (unelevated) app. It does not work after restarting as administrator, because Windows blocks drops from a lower-privilege Explorer. +- **Drag and drop**: Works because the window always runs unelevated. It does not work if the user starts Symlinker as administrator themselves, because Windows blocks drops from a lower-privilege Explorer. - **Platform**: Windows 10/11 only. ## Localization diff --git a/Symlinker/ElevatedLinker.cs b/Symlinker/ElevatedLinker.cs new file mode 100644 index 0000000..3275161 --- /dev/null +++ b/Symlinker/ElevatedLinker.cs @@ -0,0 +1,194 @@ +namespace Symlinker +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.IO.Pipes; + using System.Runtime.InteropServices; + using System.Text; + using System.Text.Json; + using System.Threading; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// + /// Creates links through a copy of Symlinker running as administrator, so the window itself + /// stays unelevated (and keeps drag and drop). Starting it shows one UAC prompt. It then waits + /// on a named pipe for link requests until disposed, so a caller can elevate before changing + /// anything on disk, create the link later, and keep using it for more links. + /// + internal sealed class ElevatedLinker : IDisposable + { + /// Command line switch that runs Symlinker as the helper instead of opening the window. + public const string HelperArg = "--link-helper"; + + private const int ErrorCancelled = 1223; + private const int HelperConnectTimeoutMs = 10000; + private static readonly TimeSpan StartTimeout = TimeSpan.FromSeconds(30); + private static readonly Encoding PipeEncoding = new UTF8Encoding(false); + + private readonly NamedPipeServerStream pipe; + private readonly Process process; + private readonly StreamReader reader; + private readonly StreamWriter writer; + + private ElevatedLinker(NamedPipeServerStream pipe, Process process) + { + this.pipe = pipe; + this.process = process; + reader = new StreamReader(pipe, PipeEncoding, false, 1024, leaveOpen: true); + writer = new StreamWriter(pipe, PipeEncoding, 1024, leaveOpen: true) { AutoFlush = true }; + } + + /// + /// Starts the helper as administrator. Returns null when the user cancels the UAC prompt. + /// Throws when the helper starts but can't be reached. + /// + public static async Task StartAsync() + { + var pipeName = "Symlinker-" + Guid.NewGuid().ToString("N"); + + // One instance only, so nothing else can open a second end with the same name + var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + Process process = null; + try + { + var startInfo = new ProcessStartInfo + { + FileName = Environment.ProcessPath, + Arguments = string.Join(" ", HelperArg, pipeName, Environment.ProcessId.ToString(CultureInfo.InvariantCulture)), + UseShellExecute = true, + Verb = "runas", + }; + + try + { + // Waits for the UAC prompt, so keep it off the UI thread + process = await Task.Run(() => Process.Start(startInfo)); + } + catch (Win32Exception exception) when (exception.NativeErrorCode == ErrorCancelled) + { + pipe.Dispose(); + return null; + } + + if (process == null) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + using var timeout = new CancellationTokenSource(StartTimeout); + var connected = pipe.WaitForConnectionAsync(timeout.Token); + var exited = process.WaitForExitAsync(timeout.Token); + await Task.WhenAny(connected, exited); + if (!connected.IsCompletedSuccessfully) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + // Make sure the other end is the helper just started, not some other program + if (!GetNamedPipeClientProcessId(pipe.SafePipeHandle, out var clientId) || clientId != (uint)process.Id) + throw new InvalidOperationException(Res.ElevationHelperFailed); + + return new ElevatedLinker(pipe, process); + } + catch + { + pipe.Dispose(); + process?.Dispose(); + throw; + } + } + + /// Whether the helper is still running and connected. + public bool IsAlive + { + get + { + try + { + return pipe.IsConnected && !process.HasExited; + } + catch (Exception) + { + return false; + } + } + } + + /// Creates a link as administrator. + public async Task CreateLinkAsync(LinkRequest request) + { + await writer.WriteLineAsync(JsonSerializer.Serialize(request)); + var line = await reader.ReadLineAsync(); + if (line == null) + throw new IOException("The administrator helper closed unexpectedly."); + + return JsonSerializer.Deserialize(line) ?? throw new IOException("The administrator helper sent an empty reply."); + } + + /// Closes the connection; the helper exits when it sees that. + public void Dispose() + { + reader.Dispose(); + writer.Dispose(); + pipe.Dispose(); + process.Dispose(); + } + + /// + /// Runs in the elevated copy: connects back to the window that started it and creates + /// each link it is sent, until the window closes the connection. Returns the exit code. + /// + public static int RunHelper(string[] args) + { + if (args.Length != 3 || !uint.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out var parentId)) + return 2; + + try + { + using var pipe = new NamedPipeClientStream(".", args[1], PipeDirection.InOut); + pipe.Connect(HelperConnectTimeoutMs); + + // Only take requests from the window that asked for elevation + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId) || serverId != parentId) + return 3; + + // Not disposed: the window closing the pipe is the normal way to finish, and + // disposing a writer then would flush into the closed pipe and throw + var reader = new StreamReader(pipe, PipeEncoding, false, 1024, leaveOpen: true); + var writer = new StreamWriter(pipe, PipeEncoding, 1024, leaveOpen: true) { AutoFlush = true }; + + string line; + while ((line = reader.ReadLine()) != null) + { + LinkResult result; + try + { + var request = JsonSerializer.Deserialize(line); + result = LinkCommand.RunAsync(request).GetAwaiter().GetResult(); + } + catch (Exception exception) + { + result = LinkResult.Failed(exception.Message); + } + + writer.WriteLine(JsonSerializer.Serialize(result)); + } + + return 0; + } + catch (Exception) + { + return 1; + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeClientProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint clientProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverProcessId); + } +} diff --git a/Symlinker/Elevation.cs b/Symlinker/Elevation.cs index aa1ba13..1b29be7 100644 --- a/Symlinker/Elevation.cs +++ b/Symlinker/Elevation.cs @@ -1,21 +1,15 @@ namespace Symlinker { using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; - using System.Text; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; - /// - /// Values the window starts with. Used to carry the form over when restarting as administrator. - /// + /// Values the window starts with, read from the command line. internal sealed class LaunchOptions { private const string ModeArg = "--mode"; @@ -58,64 +52,15 @@ public static LaunchOptions Parse(string[] args) return options; } - - /// Builds a command line that turns back into these options. - public string ToArguments() - { - var parts = new List(); - void Add(string name, string value) - { - if (!string.IsNullOrEmpty(value)) - { - parts.Add(name); - parts.Add(QuoteArgument(value)); - } - } - - Add(ModeArg, Mode); - Add(TypeArg, LinkType); - Add(LocationArg, LinkLocation); - Add(NameArg, LinkName); - Add(TargetArg, Target); - return string.Join(" ", parts); - } - - /// - /// Quotes one argument so Windows splits it back exactly as given, including spaces - /// and trailing backslashes (like "C:\"). - /// - internal static string QuoteArgument(string value) - { - if (value.Length != 0 && value.IndexOfAny(new[] { ' ', '\t', '\n', '\v', '"' }) < 0) - return value; - - var quoted = new StringBuilder("\""); - var backslashes = 0; - foreach (var c in value) - { - if (c == '\\') - { - backslashes++; - continue; - } - - // Backslashes only need escaping when a quote follows them - quoted.Append('\\', c == '"' ? (backslashes * 2) + 1 : backslashes); - quoted.Append(c); - backslashes = 0; - } - - quoted.Append('\\', backslashes * 2); - quoted.Append('"'); - return quoted.ToString(); - } } - /// Administrator rights helpers. Symlinker runs unelevated and only asks for them when needed. + /// + /// Administrator rights helpers. Symlinker runs unelevated and only elevates the link + /// creation step when needed (see ). + /// internal static class Elevation { private const int ErrorPrivilegeNotHeld = 1314; - private const int ErrorCancelled = 1223; public static bool IsElevated { @@ -155,31 +100,6 @@ public static bool CanCreateSymbolicLinks() } } - /// - /// Starts a new elevated instance with the given options. - /// Returns false when the user declines the UAC prompt. - /// - public static bool RestartElevated(LaunchOptions options) - { - var startInfo = new ProcessStartInfo - { - FileName = Environment.ProcessPath, - Arguments = options.ToArguments(), - UseShellExecute = true, - Verb = "runas", - }; - - try - { - Process.Start(startInfo)?.Dispose(); - return true; - } - catch (Win32Exception exception) when (exception.NativeErrorCode == ErrorCancelled) - { - return false; - } - } - /// /// The Windows UAC shield (small size), shown on actions that need administrator rights. /// Returns null if Windows doesn't provide it. diff --git a/Symlinker/LinkCommand.cs b/Symlinker/LinkCommand.cs new file mode 100644 index 0000000..091ca39 --- /dev/null +++ b/Symlinker/LinkCommand.cs @@ -0,0 +1,107 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// One link to create. Sent to the elevated helper as JSON, so it only holds plain values. + internal sealed class LinkRequest + { + /// "symbolic", "hard" or "junction". + public string Type { get; set; } + + /// Full path of the link to create. + public string Link { get; set; } + + /// What the link points to, as entered (a relative target stays relative). + public string Target { get; set; } + + /// Whether the link is for a folder. + public bool Directory { get; set; } + } + + /// Outcome of a , with the message to show the user. + internal sealed class LinkResult + { + public bool Success { get; set; } + + public string Message { get; set; } + + public static LinkResult Failed(string message) => new() { Success = false, Message = message }; + } + + /// Creates links with mklink. Used by the window and by the elevated helper. + internal static class LinkCommand + { + public static async Task RunAsync(LinkRequest request) + { + var arguments = BuildArguments(request); + if (arguments == null) + return LinkResult.Failed(Res.InvalidQuoteInPath); + + try + { + var startInfo = new ProcessStartInfo + { + FileName = "cmd", + Arguments = arguments, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + using var process = new Process { StartInfo = startInfo }; + process.Start(); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + var outputText = (await output).Trim(); + var errorText = (await error).Trim(); + + if (process.ExitCode == 0) + return new LinkResult { Success = true, Message = outputText.Length > 0 ? outputText : Res.LinkSuccessfullyCreated }; + + return LinkResult.Failed(errorText.Length > 0 ? errorText : outputText); + } + catch (Exception) + { + return LinkResult.Failed(Res.CmdNotFound); + } + } + + /// + /// Builds the cmd.exe arguments. Returns null for anything that could break out of the + /// quotes, since the elevated helper runs whatever it is sent. + /// + private static string BuildArguments(LinkRequest request) + { + if (request == null || string.IsNullOrWhiteSpace(request.Link) || string.IsNullOrWhiteSpace(request.Target)) + return null; + + if (request.Link.IndexOfAny(UnsafeChars) >= 0 || request.Target.IndexOfAny(UnsafeChars) >= 0) + return null; + + var typeFlag = request.Type switch + { + "hard" => "/H ", + "junction" => "/J ", + "symbolic" => string.Empty, + _ => null, + }; + + if (typeFlag == null) + return null; + + var directory = request.Directory ? "/D " : string.Empty; + return $"/c mklink {directory}{typeFlag}\"{request.Link}\" \"{request.Target}\""; + } + + // Quotes end the quoted path; line breaks end the command + private static readonly char[] UnsafeChars = { '"', '\r', '\n', '\0' }; + } +} diff --git a/Symlinker/MainWindow.Inputs.cs b/Symlinker/MainWindow.Inputs.cs index ec7db1a..750e0d3 100644 --- a/Symlinker/MainWindow.Inputs.cs +++ b/Symlinker/MainWindow.Inputs.cs @@ -31,7 +31,7 @@ public static class InputError public static void SetHasError(DependencyObject element, bool value) => element.SetValue(HasErrorProperty, value); } - /// Input checks, inline errors, launch options and the administrator restart. + /// Input checks, inline errors, launch options and administrator rights for symbolic links. public partial class MainWindow { private const string ErrorBrushKey = "Symlinker.Brushes.Error"; @@ -46,10 +46,13 @@ public partial class MainWindow private LaunchOptions launchOptions; - // Whether creating a symbolic link would need a restart as administrator + // Whether creating a symbolic link needs administrator rights (no admin, no Developer Mode) private bool symlinksNeedAdmin; private bool checkingSymlinkAccess; + // Administrator helper, started on the first symbolic link that needs it and kept until the window closes + private ElevatedLinker elevatedLinker; + private void InitializeInputs() { // The app theme is applied after the window is created, so refresh again once loaded @@ -77,6 +80,9 @@ private void InitializeInputs() if (symlinksNeedAdmin) RefreshSymlinkAccess(); }; + + // The administrator helper stays up for the whole session; closing the window ends it + Closed += (s, e) => StopElevatedLinker(); } private async void RefreshSymlinkAccess() @@ -103,22 +109,26 @@ private async void RefreshSymlinkAccess() UpdateAdminNotice(); } - /// Shows the UAC shield and the footer notice while a symbolic link would need administrator rights. + /// Whether the selected link is a symbolic link that needs administrator rights. + private bool LinkNeedsAdmin => symlinksNeedAdmin && symLinkRadio?.IsChecked == true; + + /// + /// Shows the UAC shield and the footer notice while creating the link would show a UAC + /// prompt. Once the user has approved it for this session, neither is needed. + /// private void UpdateAdminNotice() { if (adminPanel == null || createLinkShield == null || symLinkRadio == null) return; - var needsAdmin = symlinksNeedAdmin && symLinkRadio.IsChecked == true; - createLinkShield.Visibility = needsAdmin && createLinkShield.Source != null ? Visibility.Visible : Visibility.Collapsed; + var wouldPrompt = LinkNeedsAdmin && elevatedLinker?.IsAlive != true; + createLinkShield.Visibility = wouldPrompt && createLinkShield.Source != null ? Visibility.Visible : Visibility.Collapsed; adminNoticeShield.Visibility = adminNoticeShield.Source != null ? Visibility.Visible : Visibility.Collapsed; // Field errors take the same spot and matter more - adminPanel.Visibility = needsAdmin && inputErrors.Count == 0 ? Visibility.Visible : Visibility.Collapsed; + adminPanel.Visibility = wouldPrompt && inputErrors.Count == 0 ? Visibility.Visible : Visibility.Collapsed; } - private async void RestartAsAdmin_Click(object sender, RoutedEventArgs e) => await RestartAsAdminAsync(); - private void OnThemeChanged(object sender, ThemeChangedEventArgs e) => UpdateThemeBrushes(); private void UpdateThemeBrushes() @@ -170,7 +180,7 @@ static double Channel(byte value) return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); } - /// Fills the form from the command line, e.g. after restarting as administrator. + /// Fills the form from the command line. private void ApplyLaunchOptions() { var options = launchOptions; @@ -200,63 +210,56 @@ private void ApplyLaunchOptions() linkNameTextBox.Text = options.LinkName; } - private LaunchOptions GetCurrentOptions() => new() - { - Mode = isFolder ? "folder" : "file", - LinkType = hardLinkRadio.IsChecked == true ? "hard" : junctionRadio.IsChecked == true ? "junction" : "symbolic", - LinkLocation = linkLocationTextBox.Text, - LinkName = linkNameTextBox.Text, - Target = destinationLocationTextBox.Text, - }; - /// - /// Symbolic links need administrator rights unless Developer Mode is on. Checked before - /// anything runs, so nothing on disk changes when the link can't be created anyway. - /// Returns false when link creation should stop here. + /// Checks again whether a symbolic link would need administrator rights, since Developer + /// Mode may have been turned on since the window opened. /// - private async Task EnsureCanCreateLinkAsync() + private void RefreshSymlinkAccessNow() { - if (hardLinkRadio.IsChecked == true || junctionRadio.IsChecked == true) - return true; + if (symLinkRadio.IsChecked != true) + return; - // Check again: Developer Mode may have been turned on since the window opened symlinksNeedAdmin = !Elevation.CanCreateSymbolicLinks(); UpdateAdminNotice(); - if (!symlinksNeedAdmin) - return true; + } - var settings = new MetroDialogSettings - { - AnimateShow = false, - AnimateHide = false, - AffirmativeButtonText = Res.ButtonRestartAsAdmin, - NegativeButtonText = Res.ButtonNotNow, - DefaultButtonFocus = MessageDialogResult.Affirmative, - - // Smaller title so long translations fit the short window without scrolling - DialogTitleFontSize = 20, - }; + /// + /// Starts the administrator helper if this link needs it and it isn't running yet. That + /// shows one UAC prompt; the helper then stays up until the window closes, so later links + /// don't ask again. Call it before anything on disk changes, so a declined prompt leaves + /// everything as it was. Returns false when link creation should stop: the user canceled + /// the prompt (nothing is shown then) or the helper couldn't start (an error is shown). + /// + private async Task ElevateIfNeededAsync() + { + if (!LinkNeedsAdmin) + return true; - var answer = await this.ShowMessageAsync(Res.DialogElevationTitle, Res.DialogElevation, MessageDialogStyle.AffirmativeAndNegative, settings); - if (answer == MessageDialogResult.Affirmative) - await RestartAsAdminAsync(); + if (elevatedLinker?.IsAlive == true) + return true; - return false; - } + // The helper went away (e.g. ended from Task Manager); start a new one + StopElevatedLinker(); - /// Restarts as administrator with the current form values. This window closes if the user accepts the UAC prompt. - private async Task RestartAsAdminAsync() - { try { - // The new window opens with the same values; this one closes - if (Elevation.RestartElevated(GetCurrentOptions())) - Close(); + elevatedLinker = await ElevatedLinker.StartAsync(); } catch (Exception exception) { await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message, settings: FastDialog); + return false; } + + UpdateAdminNotice(); + return elevatedLinker != null; + } + + /// Closes the administrator helper, if one is running. + private void StopElevatedLinker() + { + elevatedLinker?.Dispose(); + elevatedLinker = null; } /// Checks every field, marks the bad ones and shows what's wrong. Returns true when all are fine. diff --git a/Symlinker/MainWindow.xaml b/Symlinker/MainWindow.xaml index fa9abde..ffd66b7 100644 --- a/Symlinker/MainWindow.xaml +++ b/Symlinker/MainWindow.xaml @@ -536,14 +536,9 @@ VerticalAlignment="Top" Margin="0,1,6,0"/> - - - - - + Foreground="{DynamicResource MahApps.Brushes.ThemeForeground}" + Text="{x:Static p:Resources.NoticeSymlinkNeedsAdmin}" + ToolTip="{x:Static p:Resources.NoticeSymlinkNeedsAdmin}"/>