rt,做了一个mfc程序,想阻止程序多次启动
于是在initinstance中加了如下代码:
[code=c][/ HANDLE m_hMutex = CreateMutex(NULL, FALSE, "Sample07");
// 检查错误代码
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(m_hMutex);
m_hMutex = NULL;
// 程序退出
return FALSE;
}code]
但是现在发现,在启动exe之后,第二次启动,就无法进入构造函数和initinstance方法,
感觉像是被阻塞了,如果在进程管理器中将第一次启动的程序杀死后,才能进入。
大家有遇到过这种情况么?
------解决思路----------------------
CreateMutex创建成功后在程序退出前应该ReleaseMutex,有没?
判断为ERROR_ALREADY_EXISTS后不应该调用CloseHandle。
lz说的就是防止多实例进程。
------解决思路----------------------
何必这么辛苦,阻止重复启动确实很简单,WinMain函数里的hPreInstance参数就可以用来判断是否已经有实例在运行,hPreInstance不为0,则说明已经有这个程序的实例在运行了
------解决思路----------------------
ls不知道在哪看的书,我看的参考书都说了那个参数永为0:
微软文档:
hPrevInstance [in]
Type: HINSTANCE
A handle to the previous instance of the application. This parameter is always NULL. If you need to detect whether another instance already exists, create a uniquely named mutex using the CreateMutex function. CreateMutex will succeed even if the mutex already exists, but the function will return ERROR_ALREADY_EXISTS. This indicates that another instance of your application exists, because it created the mutex first. However, a malicious user can create this mutex before you do and prevent your application from starting. To prevent this situation, create a randomly named mutex and store the name so that it can only be obtained by an authorized user. Alternatively, you can use a file for this purpose. To limit your application to one instance per user, create a locked file in the user's profile directory.
------解决思路----------------------
#define MAX_INS 1
///////////////////////// for one instance //////////////////
// tell compiler
#pragma data_seg ("Shared")
long preins=0;// has to been initialized
#pragma data_seg ()
// tell link
#pragma comment (linker," -section:Shared,rws")
BOOL CxxxApp::InitInstance()
{
///////////// one or two instances only /////////////////
preins++;
if (preins>MAX_INS) return FALSE;// only 1 window
/////////////////////////////////////////////////
------解决思路----------------------
你创建Mutex的目的,就是希望第二次启动的时候,第二个进程实例退出吧。可以退出前,把第一个实例呼唤到前台
------解决思路----------------------
HANDLE hMutex = CreateMutex(NULL, false, "Process");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
MessageBox(Application->Handle, "程序已经在运行中,不能重复启动!", "提示", MB_OK +MB_ICONWARNING);
Application->Terminate();
return 0;
}