55using System . Threading . Tasks ;
66using System . IO ;
77using System . Net ;
8+ using System . Threading ;
89using System . Windows . Forms ;
910using Microsoft . Win32 ;
1011
1112namespace 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