-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
104 lines (92 loc) · 3.42 KB
/
Program.cs
File metadata and controls
104 lines (92 loc) · 3.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using Serilog;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
[assembly: CLSCompliant(true)]
namespace Memento
{
static class Program
{
sealed class BringToTopReceiver : NativeWindow, IDisposable
{
private readonly Action _onShow;
public BringToTopReceiver(Action onShow)
{
_onShow = onShow;
// Create an invisible top-level window.
CreateHandle(new CreateParams
{
Caption = "Memento.ShowMeReceiver",
X = 0,
Y = 0,
Height = 0,
Width = 0,
Style = 0
});
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SHOWME)
{
_onShow();
return;
}
base.WndProc(ref m);
}
public void Dispose() => DestroyHandle();
}
static Mutex mutex = new Mutex(false, @"Global\{RO-54B7C3B0-A785-40B9-AFFF-397247B83F84}");
public const int HWND_BROADCAST = 0xffff;
public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME.{RO-54B7C3B0-A785-40B9-AFFF-397247B83F84}");
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);
[STAThread]
static void Main()
{
if (mutex.WaitOne(TimeSpan.Zero, false))
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Forms.Memento mainForm = new();
using var receiver = new BringToTopReceiver(() =>
{
if (!mainForm.IsHandleCreated) return;
mainForm.BeginInvoke(new Action(() =>
{
mainForm.BringToTop();
}));
});
Application.Run(mainForm);
mutex.ReleaseMutex();
}
else
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
PostMessage(
HWND_BROADCAST,
WM_SHOWME,
IntPtr.Zero,
IntPtr.Zero);
}
else
{
Console.WriteLine("The application is already running");
}
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var log = new LoggerConfiguration().WriteTo.File("unhandled.log", rollingInterval: RollingInterval.Day).CreateLogger();
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex?.ToString() ?? "Unhandled exception");
log.Fatal(ex, "Unhandled exception");
Environment.FailFast("Unhandled exception", ex);
}
}
}