This is fundamentally a Windows API question, so the solution is the same in all languages: call the GetSystemMetrics
API function, requesting the SM_CLEANBOOT
metric. This will return an integer value indicating how the system was booted. In particular:
- 0 means a normal boot,
- 1 means a fail-safe ("safe mode") boot,
- 2 means a fail-safe boot with networking support.
The only challenge, then, is how to call this function from managed code. The .NET Framework and C# language allow you to P/Invoke native functions. To do so, you need to provide a declaration of the native function you want to call, and you'll also want to define some types (enumerations, etc.). Sample code:
internal const int SM_CLEANBOOT = 67;
[DllImport("user32.dll")]
internal static extern int GetSystemMetrics(int smIndex);
A more complete code sample, including a full enumerated type for all of the system metrics is available on pinvoke.net.
Note that what Steve and Rand Random mentioned in comments is correct. In safe mode, your application will not be launching automatically—and you shouldn't want it to. This detection is something you'll need to do manually at application startup, and only if you are actually going to behave differently.
Don't assume that the user booting up in safe mode implies that they want to enter recovery mode in your program. System problems and application problems are completely independent. You should simply provide a way to enter recovery mode as part of your application—perhaps a command-line switch. Don't use a global solution for a local problem.