Search code examples
c#exceptionexitmonogameentry-point

C# - Entry point check for OS


So my Program.cs looks like this:

using System;
using System.Windows.Forms;
using myProj.GameScreens;

namespace myProj
{
#if WINDOWS
    /// <summary>
    /// The main class.
    /// </summary>
    public static class Program
    {
        static StartScreen startScreen;
        static MainGame mainGame;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            mainGame = new MainGame();
            startScreen = new StartScreen();
            Application.EnableVisualStyles();

            if (startScreen.ShowDialog() == DialogResult.OK) mainGame.Run();
        }
    }
#else
    System.Environment.Exit(1);
#endif
}

So my question is could I actually do something like this? Is the code within the #else directive reachable? How to exit the application if it's not started from a windows OS? Or could I use an Exception? Win32Exception wouldn't work on other OS's so what can I do? Is the code going to exit even without the #else?

option #1: exit the app if not windows

option #2: tell the user that the app requires windows AND exit (maybe a custom exception? Also that's preferred.)

I have some code that depends heavily on [DllImport("user32.dll"] so I can only work with windows. Yes, you guessed it right, it's a Windows MonoGame entry point class.


Solution

  • This won't work as the #if is a compile time operation that changes how the executable is generated.

    If you compiled this on Windows and tried to run it somewhere else it would attempt (and fail) to run the program.

    You need to write code for a run time check of the operating system. The Environment.OSVersion property is probably what you need, but it returns a string that you'll need to parse. Also note:

    In some cases, the OSVersion property may not return the operating system version that matches the version specified for the Windows Program Compatibility mode feature.

    Source

    As to how you act, there's no need to explicityy call Exit. If you don't do anything else your program will stop anyway. Although your test will have to be inside Main.