-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
81 lines (68 loc) · 2.99 KB
/
Copy pathProgram.cs
File metadata and controls
81 lines (68 loc) · 2.99 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
using System.Windows.Forms;
using System.Threading;
using System;
/// <summary>
/// The main entry point for the application.
/// </summary>
namespace RoundedFormsExample
{
internal static class Program
{
/// <summary>
/// Main method – guards against multiple instances, enables WinForms
/// visual styles, and starts the UI via <see cref="AppContextManager" />.
/// </summary>
[STAThread]
static void Main()
{
// Unique name for the mutex that enforces a single instance.
string SingleInstanceMutexName = Application.ProductName;
// Try to acquire the global mutex.
bool isFirstInstance;
using var mutex = new Mutex(initiallyOwned: true,
name: SingleInstanceMutexName,
createdNew: out isFirstInstance);
if (!isFirstInstance) return; // Another copy is already running – quietly exit.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new AppContextManager());
// GC.KeepAlive(mutex); // Now unnecessary with the using‑statement.
}
#region Nested ApplicationContext
/// <summary>
/// Custom context lets us close and reopen <see cref="MainForm"/> without
/// killing the message loop or losing the single‑instance mutex.
/// </summary>
private sealed class AppContextManager : ApplicationContext
{
public AppContextManager() => ShowMain();
/// <summary>
/// Instantiates and shows a new <see cref="MainForm"/>.
/// </summary>
private void ShowMain()
{
var main = new MainForm();
this.MainForm = main; // Let ApplicationContext watch it.
// Event handler that restores native chrome and restarts form.
void RestoreHandler(object? sender, EventArgs e)
{
main.RestoreNativeRequested -= RestoreHandler;
main.FormClosed -= Main_FormClosed;
main.Close(); // Dispose current form.
ShowMain(); // Open a fresh one.
}
// Wire up events.
main.RestoreNativeRequested += RestoreHandler;
main.FormClosed += (s, e) => ExitThread(); // Keep handler.
// Show the window (non‑modal).
main.Show();
}
/// <summary>
/// Ends the message loop when the main form closes.
/// </summary>
private void Main_FormClosed(object? sender, FormClosedEventArgs e) =>
ExitThread(); // Base class method – stops Application.Run.
}
#endregion
}
}