program Project1; uses Windows, Forms, Unit1 in 'Unit1.pas' {Form1}, Function_U in 'E:\工作\JJQDS_V2\Function_U.pas', Config_U in 'E:\工作\JJQDS_V2\Config_U.pas'; {$R *.res} var hAppMutex : THandle; begin Application.Initialize; hAppMutex := CreateMutex(nil,False,PChar('{19D51511-8490-42AC-B677-E3D59AF822B1}')); if hAppMutex = 0 then begin MessageBox(0,PChar('创建互斥对象失败!'),PChar('Error'),MB_OK + MB_ICONINFORMATION); Exit; end; if (hAppMutex <> 0) and (GetLastError = ERROR_ALREADY_EXISTS) then begin MessageBox(0,PChar('不是第一次运行这个程序!'),PChar('OK'),MB_OK + MB_ICONINFORMATION); CloseHandle(hAppMutex); Exit; end; Application.CreateForm(TForm1, Form1); Application.Run; CloseHandle(hAppMutex);end. ======================================================================= m_hMutex=CreateMutex(NULL,FALSE,m_pAppName); //HANDLE m_hMutex; if(GetLastError()==ERROR_ALREADY_EXISTS) { HWND hWnd=::FindWindow(NULL,m_pAppName); if(hWnd) { if(::IsIconic(hWnd)) ::ShowWindow(hWnd,SW_RESTORE); ::SetForegroundWindow(hWnd); ::SetForegroundWindow(::GetLastActivePopup(hWnd)); } else MessageBox(NULL,"您的程序已经运行了","提示信息",MB_ICONINFORMATION); return FALSE; } ======================================================================== 以下代码尚不能激活已经运行的实例,你试着该以下吧,改好请贴出来。 //在 InitInstance 中,创建信号量: HANDLE hSem = CreateSemaphore(NULL,1,1,m_pszAppName); //信号量已存在? if(GetLastError() == ERROR_ALREADY_EXISTS) { //关闭信号量句柄 CloseHandle(hSem); //寻找先前实例的主窗口 HWND hWndPrevious = ::GetWindow(::GetDesktopWindow(),GW_CHILD); while(::IsWindow(hWndPrevious)) { //检查窗口是否有预设的标记? //有,则是我们寻找的主窗口 if(::GetProp(hWndPrevious,m_pszAppName)) { //主窗口已经最小化,则恢复其大小 if(::IsIconic(hWndPrevious)) ::ShowWindow(hWndPrevious,SW_RESTORE); //将主窗口激活 ::SetForegroundWindow(hWndPrevious); //将主窗口对话框激活 ::SetForegroundWindow(::GetLastActivePopup(hWndPrevious)); //退出本实例 reture FALSE; } else //继续寻找下一个窗口 hWndPrevious = ::GetWindow(hWndPrevious,GW_HWNDNEXT); } //前一实例已存在,但找不到其主窗口 //可能出错了 //退出本实例 return FALSE; }

评论