0

I have a C# WinForms app in which I need to do some pre-checks before running the full application. One of those checks for example, is to make sure the application is running with administrative privileges.

Problem is, these checks are done during the constructor of my application's main class. So if I try to exit using Application.Exit() while in the constructor, it doesn't work. I know there's reason that this Application.Exit() works after construction is complete, how how do I gracefully exit the application during the constructor call ?

I couldn't find any Stack Overflow showing such an answer WITH a code example.

NOTE: Checking for administrative privileges is just one of several different checks I do during the constructor call, so please don't suggest a solution specifically solving JUST for this check I've shown as an example.

My code:

In the code below, I will see the "Exiting" message box, but the executable never actually ends - it keeps running.

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new SomeClass());
    }
}

class SomeClass : ApplicationContext
{
    public SomeClass()
    {
        if (!RunningAsAdministrator())
        {
            MessageBox.Show("Exiting");
            Application.Exit();
        }
    }

    public static bool RunningAsAdministrator()
    {
        return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
                  .IsInRole(WindowsBuiltInRole.Administrator);
    }

}
Ahmad
  • 12,886
  • 30
  • 93
  • 146
  • Move your check code in `static void Main` and only call `Application.Run` if it passes? – GSerg Apr 30 '20 at 07:05
  • That's not a viable solution for me as it would be a big change unfortunately. – Ahmad Apr 30 '20 at 07:07
  • 1
    The [MSDN example](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.run?view=netcore-3.1#System_Windows_Forms_Application_Run_System_Windows_Forms_ApplicationContext_) uses `ExitThread()`. – GSerg Apr 30 '20 at 07:09
  • 2
    Related/Possible duplicate: https://stackoverflow.com/questions/554408/why-would-application-exit-fail-to-work tldr: try `Environment.Exit`. – Sweeper Apr 30 '20 at 07:22
  • Yes I saw that thread ... But `Environment.Exit()` isn't a clean exit so I wanted to avoid that if possible. – Ahmad May 01 '20 at 11:57

0 Answers0