Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi All:

I added the following code in OnInitDialog() to let the program do the thing which is:
it can't open the same program when the program has executed!
C++
BOOL COneInstanceDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	SetIcon(m_hIcon, TRUE);		
	SetIcon(m_hIcon, FALSE);		


	HANDLE hMutex;
	hMutex=CreateMutex(NULL,true,_T("Test program"));
	if(hMutex)
	{
		if(ERROR_ALREADY_EXISTS==GetLastError())
		{
		    //MessageBox(_T("The program has executed"),MB_OK);
		    ExitProcess(0); //close program
		}
	}
	return TRUE;
}

But if I wanna do the next step:
The program has executed when you open it again,
and it will call and show the ex-program you have opened.

How can I do?

Thanks a lot!!
Posted

1 solution

I think you don't use Mutex correctly, take a look at the documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682411%28v=vs.85%29.aspx[^]

Return value
If the function succeeds, the return value is a handle to the newly created mutex object.
If the function fails, the return value is NULL. To get extended error information, call GetLastError
.

That means you need something like this:

C++
BOOL COneInstanceDlg::OnInitDialog()
{
	...	
 
	HANDLE hMutex;
	hMutex=CreateMutex(NULL,true,_T("Test program"));
	if(NULL == hMutex)
	{
		if(ERROR_ALREADY_EXISTS==GetLastError())
		{
		    //MessageBox(_T("The program has executed"),MB_OK);
		    ExitProcess(0); //close program
		}
	}

	return TRUE;
}


P.S.: Apart of this I would make m_hMutex a member variable of your COneInstanceDlg class to have the chance to release the mutex after your program exits.
 
Share this answer
 
v2
Comments
Member 10307999 4-Mar-14 21:19pm    
Dear du[DE]:
Thanks for your response, but I still don't have a idea...
Would you specify it concretely?
Thank you!!
Member 10307999 4-Mar-14 22:41pm    
I think whether I can call a existing program through lpName(in my case, it's the "Test program")?
But I cannot find the relative functions...
Leo Chapiro 5-Mar-14 4:46am    
Hi Member 10307999738,

Have you tried to change your func COneInstanceDlg::OnInitDialog() accordingly my advice: simple changing "if(hMutex)" to "if(NULL == hMutex)" ? I mean, this simple change should already work!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900