views:

265

answers:

4

There are a lot of solutions for restricting an application from running twice. Searching by process name, using a named mutex etc. But I all of these methods don't work if I want to restrict my application to the shell session.

A user may have more than login session and shell on windows (right?)? If this is true I want to be able to run one instance of my application in every shell session but allow only one.

Is there a way to get a shell identifier which could then be put into the mutex name?

A: 

The shell identifier you want to use is the user name. This is available as Environment::UserName or GetUserName()

Byron Whitlock
+4  A: 

You can create local (session only) or global (whole system) mutexes. See http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx for more info. Look for global and local.

Patrick
+1 yes, good call
Byron Whitlock
see here for an example: http://kristofverbiest.blogspot.com/2008/11/creating-single-instance-application.html
x4u
This works for WIN32-api, too. I did not see Local\ and Global\ in the examples. http://msdn.microsoft.com/en-us/library/ms682411%28VS.85%29.aspx
Wienczny
A: 

You can go from process id of the current process to a WTS session ID, I think that will do what you need. ProcessIdToSessionId

You should be aware that a terminal services session can be disconnected from one desktop and then connected to by another, so the 'shell' can actually change, but the session ID should remain the same.

John Knoeller
A: 

If you want to restrict it to one instance per login session, even if the same user account has multiple login sessions running at the same time (Server/Terminal Server) you could use the handle from GetShellWindow to check if there is a instance running already for this desktop.

x4u