-
Roger
Hello everyone,
I wrote an application using VC++.
How do I prevent a user from running it when another one is already
running? In short, what are the codes for detecting that another version
is already running?
The amateurish way is to wrong something to a temp file but this
will not work if the application crash halfway.
Please reply.
Thanks.
regards,
ywshum
-
Re: Roger
Hi,
I think you can find the instance using FindWindow.
Suppose your application has a caption IDS_CAPTION
CString szCaption;
szCaption.LoadString(IDS_CAPTION);
HWND hWnd = FindWindow(NULL, szCaption);
if (!hWnd) return FALSE;//no instance found
AfxMessageBox(IDS_EXIST);//if an instance found messagebox that an
//instance already exists
return TRUE;
Then based on the return value of this you can stop running another instance.
Thanks,
Reshmi
-
Re: Roger
you can create a CMutex object with your own special string as a name for it
if you can create the CMutex, this is the first instance, and when the app exists you close the CMutex
if you can not create it, your app is already running
Sally
-
Re: Roger
BOOL CAIAWashChartApp::InitInstance()
{
AfxEnableControlContainer();
// Allow to run only single instance of ControlWoks
HWND hwnd = ::FindWindow(0, "AIA ControlWorks");
if(NULL != hwnd)
{
TRACE("One Instance of ControlWorks is already running\n");
if(::IsIconic(hwnd))
{
::ShowWindow(hwnd, SW_RESTORE);
}
else
{
::SetForegroundWindow(hwnd);
}
return FALSE;
}
.
.
.
.
}
-
Re: Roger
Hi. Try this!
In the App's .H -file add a CEvent *.
#include <afxmt.h> // CEvent
class YourApp : public CWinApp
{
...
...
...
private:
CEvent* m_pInstanceEvent;
};
// Add this In the App's .cpp -file //
/////////////////////////////////////////////////////////////////////////////
// CYourApp construction
CYourApp::CYourApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
m_pInstanceEvent = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CYourApp destruction
CYourApp::~CYourApp()
{
// kill the instance handle
if (m_pInstanceEvent != NULL)
{
delete m_pInstanceEvent;
m_pInstanceEvent = NULL;
}
}
BOOL CYourApp::InitInstance()
{
// Do we already have an Instance of the App?
m_pInstanceEvent = new CEvent(FALSE, FALSE, AfxGetAppName());
if (::GetLastError() == ERROR_ALREADY_EXISTS)
{
// End this Instance
m_pInstanceEvent->SetEvent();
return FALSE;
}
...
...
...
return TRUE;
}
Good Luck!
/Peter Lundqvist