Link to home
Create AccountLog in
Avatar of AndyAinscow
AndyAinscowFlag for Switzerland

asked on

Set first instance of app to foreground when attempting to start a further instance

I'm using a local named mutex to ensure that only one instance of an app is running within a session.  (This works).

What I would like to do is activate and set as foreground window this app when the user attempts to start a second instance - they can't create the mutex.


I know I could iterate all processes until I find the first instance but is there a simple way to find the process ID (or active window handle) of the owner of the mutex.

ASKER CERTIFIED SOLUTION
Avatar of dfke
dfke

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account

Just for giggles, I threw this question over to ChatGPT, who promptly told me that it was absolutely possible. All you had to do was:


(A) use an exception would never be thrown. Then...

(B) get the owner ID (the SID) of the mutex and extract the last set of digits from the SID. Then...

(C) translate those last digits to a number, and then look up the process ID for that number.


Wow. Sometimes I wonder where it got its training material from. The only thing I can think of is that somewhere out there, some developer decided to create a new security principal for each process (!!!) and injected the process ID onto the end of the SID, so that the second app run could grab the PID from the owning SID. Talk about using a bulldozer to swat a fly...

Alternatively, if shared memory space or named pipes or the like is still overkill, just use a common file. Have the mutex owner acquire a lock and write its PID to the file, then subsequent processes can read the file if they aren't the mutex owners.

Avatar of AndyAinscow

ASKER

Thanks, I'll look closer next week.

>>If the reason you're asking about this is because you're concerned about an app being copied/renamed a ...


No, well not really but it can happen in some cases, I just wondered if there was a simple way I didn't know about.

SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account

Thanks to all for the code and comments.  So the answer to my question was basically no.


I'd forgotton about HWND_BROADCAST and RegisterWindowsMessage - I'd used them many years ago.  That may well be safer than any enumerating or iterating through process technique method.