How to allow only one application instance

The following code will ensure that your application can only have one instance active. If the user tries to open the application again while the application is already running then the application will simply quit (in this case after showing a message).

For this to work we will need to modify the Program.cs to check with the use of Mutex if the application is already running or not before we open the main form. Our check will take place in the Main method.

Your code in Program.cs should look like this:

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

usingSystem;

usingSystem.Reflection;

usingSystem.Runtime.InteropServices;

usingSystem.Threading;

usingSystem.Windows.Forms;

namespaceWindowsFormsApplication1

{

staticclassProgram

{

[STAThread]

staticvoidMain()

{

/* Retrieve the application Guid attribute. Alternative you can simply use the application name to initialize the Mutex

* but it might be risky as other programs might have similar name and make use of the Mutex class as well. */