diff --git a/OneCleaner/App.config b/OneCleaner/App.config index 88fa402..d1428ad 100644 --- a/OneCleaner/App.config +++ b/OneCleaner/App.config @@ -1,6 +1,6 @@ - + - + - \ No newline at end of file + diff --git a/OneCleaner/App.xaml b/OneCleaner/App.xaml index b857312..8af9a20 100644 --- a/OneCleaner/App.xaml +++ b/OneCleaner/App.xaml @@ -2,8 +2,9 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:OneCleaner" - StartupUri="MainWindow.xaml"> + StartupUri="MainWindow.xaml" + Startup="App_Startup" > - + diff --git a/OneCleaner/App.xaml.cs b/OneCleaner/App.xaml.cs index 7e16426..983b2a1 100644 --- a/OneCleaner/App.xaml.cs +++ b/OneCleaner/App.xaml.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; -using System.Configuration; -using System.Data; -using System.Linq; -using System.Threading.Tasks; +using System.Diagnostics; +using System.Reflection; +using System.Security.Principal; using System.Windows; namespace OneCleaner @@ -13,5 +11,41 @@ namespace OneCleaner /// public partial class App : Application { + private bool IsRunAsAdministrator() + { + var windowsIdentity = WindowsIdentity.GetCurrent(); + var windowsPrincipal = new WindowsPrincipal(windowsIdentity); + + return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator); + } + + private void App_Startup(object sender, StartupEventArgs e) + { + if (!IsRunAsAdministrator()) + { + // It is not possible to launch a ClickOnce app as administrator directly, so instead we launch the + // app as administrator in a new process. + var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase) + { + // The following properties run the new process as administrator + UseShellExecute = true, + Verb = "runas" + }; + + // Start the new process + try + { + Process.Start(processInfo); + } + catch (Exception) + { + // The user did not allow the application to run as administrator + MessageBox.Show("Sorry, this application must be run as Administrator."); + } + + // Shut down the current process + Application.Current.Shutdown(); + } + } } } diff --git a/OneCleaner/MainWindow.xaml b/OneCleaner/MainWindow.xaml index 85c1b58..28f2365 100644 --- a/OneCleaner/MainWindow.xaml +++ b/OneCleaner/MainWindow.xaml @@ -1,11 +1,12 @@ - + Title="OneCleaner" Height="350" Width="525" Loaded="Window_LoadedAsync" Icon="icon.ico"> @@ -47,7 +48,7 @@ - +