Skip to content

Commit 3c797bd

Browse files
committed
Allow only one instance of app to run at a time
1 parent a469ae5 commit 3c797bd

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/FormWrapper.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55
using System.Threading.Tasks;
66
using System.IO;
77
using System.Net;
8+
using System.Threading;
89
using System.Windows.Forms;
910
using Microsoft.Win32;
1011

1112
namespace WinDynamicDesktop
1213
{
1314
class FormWrapper : ApplicationContext
1415
{
16+
private Mutex _mutex;
1517
private ProgressDialog downloadDialog;
1618
private InputDialog locationDialog;
1719
private NotifyIcon notifyIcon;
@@ -22,6 +24,7 @@ class FormWrapper : ApplicationContext
2224
public FormWrapper()
2325
{
2426
Application.ApplicationExit += new EventHandler(OnApplicationExit);
27+
EnforceSingleInstance();
2528
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(OnPowerModeChanged);
2629

2730
JsonConfig.LoadConfig();
@@ -44,6 +47,22 @@ public FormWrapper()
4447
}
4548
}
4649

50+
private void EnforceSingleInstance()
51+
{
52+
bool isNewInstance;
53+
_mutex = new Mutex(true, @"Global\WinDynamicDesktop", out isNewInstance);
54+
55+
GC.KeepAlive(_mutex);
56+
57+
if (!isNewInstance)
58+
{
59+
MessageBox.Show("Another instance of WinDynamicDesktop is already running.", "Error",
60+
MessageBoxButtons.OK, MessageBoxIcon.Warning);
61+
62+
Environment.Exit(0);
63+
}
64+
}
65+
4766
private void InitializeComponent()
4867
{
4968
notifyIcon = new NotifyIcon
@@ -122,8 +141,9 @@ public void DownloadImages()
122141
if (imagesNotFound)
123142
{
124143
MessageBox.Show("Images folder not found. The program will quit now.", "Error",
125-
MessageBoxButtons.OK, MessageBoxIcon.Error);
126-
Environment.Exit(1);
144+
MessageBoxButtons.OK, MessageBoxIcon.Warning);
145+
146+
Environment.Exit(0);
127147
}
128148

129149
downloadDialog = new ProgressDialog();

0 commit comments

Comments
 (0)