0

Got curious when someone down-voted this code as a solution to running only a single instance of an application without stating why they did so.

 int hWnd = FindWindow(null, "My Application Title");
 if (hWnd > 0) //If found
 {
     Process.GetCurrentProcess().WaitForExit(600);
     try
     {
        SetForegroundWindow(hWnd); //Activate it
        ShowWindow(hWnd, 9);
        Process.GetCurrentProcess().Kill();
     }
     catch (Exception ex)
     {
        //write to log
     }
 }

 //Import the FindWindow API to find our window
 [DllImport("User32.dll")]
 public static extern int FindWindow(String ClassName, String WindowName);
 //Import the SetForeground API to activate it
 [DllImport("User32.dll")]
 public static extern IntPtr SetForegroundWindow(int hWnd);
 //Import the ShowWindow API to show it
 [DllImport("User32.dll")]
 public static extern bool ShowWindow(int hWnd, int nCmdShow);

Could someone be kind as to explain the drawbacks of this method to me? Thanks.

Community
  • 1
  • 1
Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65

2 Answers2

4

Because if the application is starting twice (accidental clicking), there is a small window of time where the test will fail. Both instances could be starting but neither has created a window yet.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • hmmm, makes some sense. This could happen in a very slow PC, I agree. – Chibueze Opata Mar 15 '12 at 19:19
  • 1
    On any machine, just not yours :). You are explicitly adding race condition that will happen very rarely, so the application will slowly become know as "the one you need to start very carefully, otherwise restart machine and try again". You will not be able to find reason on you own machine it will never happen when you are watching... – Alexei Levenkov Mar 15 '12 at 19:53
  • lol @AlexeiLevenkov Funny, I've had a similar *user tell-story* experience before. – Chibueze Opata Mar 15 '12 at 20:10
1

The drawbacks as far as I can see are that it is overly complicated for what should be a simple solution. You do not need to crack into the windows api to force a single instance of an api. I would guess that is why you got downvoted.

If you follow the links in the Uwe's answer, you will see that you can remain in managed code, which should be your default unless there is some reason you MUST dig a little deeper.

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • what exactly is *slightly* wrong about using WINAPI? I don't see anything wrong with it. – Chibueze Opata Mar 15 '12 at 19:25
  • 1
    I have no problem using the windows API, however there are managed wrappers that you can use. All I am trying to get at is that unmanaged code is more dangerous and requires more care, so why take the risk? – Justin Pihony Mar 15 '12 at 19:42