Restart Single Instance Application in Administrator Mode

Introduction

This article describe how to restart a single instance WinForm application in administrator mode programmatically when required. Sometimes, we want to run our application in administrator mode to run certain functions but we don't want the application to always run in administrator mode.

The easiest implementation is to modify the application manifest file to tell application to start in administrator mode always. ( Reference: StackOverflow - How to force my C# Winforms program run as administrator on any computer? ) However, that's also means that user must have administrator rights in order to use your application. User who does not have administrator rights will not able to use our application.

 

Single Instance Application

Implementation of single instance application is simple by introducing a mutex object in Program class. mutex.WaitOne in Program.cs ensure only one instance in running at a time.

For normal startup, WaitOne is returned immediately whereas 10 seconds delay is added on restart loop to wait for previous instance to terminate. An argument is /restart is added to command line to tell the application that this is internal restart.

 

Restart Application into Administrator Mode by Code

To restart an application itself into Administrator mode, we used CodeArtEng.Diagnostics.ProcessExecutor to launch application with RunAsAdministrator set. 

Remember that command line argument /restart is added to tell application that this is internal restart, and it should wait for up to 10 seconds on startup. Once the new instance is started, the application terminate by calling Application.ExitThread(). It is important to make sure the application exit as soon as possible in order for the new instance to launch.

Code snippets as follow:

Popular posts from this blog

(AGauge) WinForms Gauge Control - Discontinued

C# DSP Simulation - DSP Lab

WinForms Controls