|
| 1 | +using System; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | +using System.Threading; |
| 4 | +using Microsoft.UI.Dispatching; |
| 5 | +using Microsoft.UI.Xaml; |
| 6 | +using Microsoft.Windows.AppLifecycle; |
| 7 | +using WinRT; |
| 8 | + |
| 9 | +namespace Coder.Desktop.App; |
| 10 | + |
| 11 | +#if DISABLE_XAML_GENERATED_MAIN |
| 12 | +public static class Program |
| 13 | +{ |
| 14 | + private static App? app; |
| 15 | +#if DEBUG |
| 16 | + [DllImport("kernel32.dll")] |
| 17 | + private static extern bool AllocConsole(); |
| 18 | +#endif |
| 19 | + |
| 20 | + [DllImport("user32.dll", CharSet = CharSet.Unicode)] |
| 21 | + private static extern int MessageBoxW(IntPtr hWnd, string text, string caption, int type); |
| 22 | + |
| 23 | + [STAThread] |
| 24 | + private static void Main(string[] args) |
| 25 | + { |
| 26 | + try |
| 27 | + { |
| 28 | + ComWrappersSupport.InitializeComWrappers(); |
| 29 | + if (!CheckSingleInstance()) return; |
| 30 | + Application.Start(p => |
| 31 | + { |
| 32 | + var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread()); |
| 33 | + SynchronizationContext.SetSynchronizationContext(context); |
| 34 | + |
| 35 | + app = new App(); |
| 36 | + app.UnhandledException += (_, e) => |
| 37 | + { |
| 38 | + e.Handled = true; |
| 39 | + ShowExceptionAndCrash(e.Exception); |
| 40 | + }; |
| 41 | + }); |
| 42 | + } |
| 43 | + catch (Exception e) |
| 44 | + { |
| 45 | + ShowExceptionAndCrash(e); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + [STAThread] |
| 50 | + private static bool CheckSingleInstance() |
| 51 | + { |
| 52 | +#if !DEBUG |
| 53 | + const string appInstanceName = "Coder.Desktop.App"; |
| 54 | +#else |
| 55 | + const string appInstanceName = "Coder.Desktop.App.Debug"; |
| 56 | +#endif |
| 57 | + |
| 58 | + var instance = AppInstance.FindOrRegisterForKey(appInstanceName); |
| 59 | + return instance.IsCurrent; |
| 60 | + } |
| 61 | + |
| 62 | + [STAThread] |
| 63 | + private static void ShowExceptionAndCrash(Exception e) |
| 64 | + { |
| 65 | + const string title = "Coder Desktop Fatal Error"; |
| 66 | + var message = |
| 67 | + "Coder Desktop has encountered a fatal error and must exit.\n\n" + |
| 68 | + e + "\n\n" + |
| 69 | + Environment.StackTrace; |
| 70 | + MessageBoxW(IntPtr.Zero, message, title, 0); |
| 71 | + |
| 72 | + if (app != null) |
| 73 | + app.Exit(); |
| 74 | + |
| 75 | + // This will log the exception to the Windows Event Log. |
| 76 | +#if DEBUG |
| 77 | + // And, if in DEBUG mode, it will also log to the console window. |
| 78 | + AllocConsole(); |
| 79 | +#endif |
| 80 | + Environment.FailFast("Coder Desktop has encountered a fatal error and must exit.", e); |
| 81 | + } |
| 82 | +} |
| 83 | +#endif |
0 commit comments