Once again, I was working on a future CodeProject article, and decided that I wanted to force one of the applications in the solution to be run in admin mode so that the processing in that application could be performed without interference from the UAC. Because the whole application needs to run in admin mode, and because there may be times when I might want to run several subsequent forms from the Main method, I put this code into the Main method so that the form(s) won't even run if the app isn't in admin mode. Doing it this way also keeps me from having to add special code to any form that might become the main form. Here's the main method, in all it's glory.
using System.Security.Prinicipal;
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
{
MessageBox.Show("You must run this application as administrator. Terminating.");
Application.Exit();
}
Application.Run(new FormMain());
}
catch (Exception ex)
{
if (ex != null) {}
}
}