PDA

View Full Version : How to detect that first instance of application is already running?



igor71
9th June 2008, 06:23
Hello,
i'd like to know if there is a Qt way to detect if one instance of application is already running in memory?
What i'm trying to do :
If user launches my app it should check if it is already in memory (first copy) and if it is, than show a main window of first copy.
I'm on WinXP with Qt 4.4.0
Is there some nifty Qt class or method for that?
Actually i have a solution with a thread and socket listening to local port, but it's not qt.
So, Qt way of doing this?

igor71
9th June 2008, 07:14
http://www.qtcentre.org/forum/showthread.php?t=11824&highlight=detect+running
:(
seems that is a Qt way - QtSingleApplication, but it's in solution area and not free.
May be Qt architectors will move this needful class into main package in the future...
So i'm on my own solution with locally started thread listening to socket.

ChristianEhrlicher
9th June 2008, 07:55
You should search more next time :)
http://wiki.qtcentre.org/index.php?title=SingleApplication

lyuts
9th June 2008, 09:22
You can use Singleton pattern (if I'm not mistaken).

steg90
9th June 2008, 09:44
Singleton Pattern is useful for creating just one instance of a class / object...

Try :



#pragma once

#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H

class CLimitSingleInstance
{
protected:
DWORD m_dwLastError;
HANDLE m_hMutex;

public:
CLimitSingleInstance(TCHAR *strMutexName)
{
//Make sure that you use a name that is unique for this application otherwise
//two apps may think they are the same if they are using same name for
//3rd parm to CreateMutex
m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
m_dwLastError = GetLastError(); //save for use later...
}

~CLimitSingleInstance()
{
if (m_hMutex) //Do not forget to close handles.
{
CloseHandle(m_hMutex); //Do as late as possible.
m_hMutex = NULL; //Good habit to be in.
}
}

BOOL IsAnotherInstanceRunning()
{
return (ERROR_ALREADY_EXISTS == m_dwLastError);
}
};
#endif


In your main.cpp :




CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{B5D47D64-F5F9-46e3-AFB8-EC34D0F863F1}"));

if (g_SingleInstanceObj.IsAnotherInstanceRunning())
{
QMessageBox::critical(NULL, "Warning",
"There is another instance of this application already running." );
return FALSE;
}



;)

Regards,
Steve

igor71
9th June 2008, 11:21
Wow!
Thanks, guys!