Главная страница | назад





Article #17581: Preventing another instance of your application.

 Question and Answer Database
FAQ2581C.txt Preventing another instance of your application.
Category :VCL
Platform :All
Product :C++Builder 3.x
Question:
How do I prevent another instance of my application fromj comming up
if there is one already running?
Answer:
This code will prevent a BCB application from running another
instance. Instead, it finds and brings to the forefront the previous
instance. Now it also restores the other instance even if it was
iconic. Put the following in WinMain() with your own Class Names,
Application Title, and Mutex name.
::CreateMutex(NULL, FALSE, "YourMutexName");
if ( GetlastError() == ERROR_ALREADY_EXISTS )
{
// Found another running application with the same mutex
// so one instance is already running.
Application->Title="Testing"; // prohibits finding this instance
HWND FirsthWnd, FirstChildhWnd;
FirsthWnd = ::FindWindow("TApplication", "YourApplicationTitle"); // see Application->Title or Options|Project|Application Tab|Title
if (::IsIconic(FirsthWnd))
::ShowWindow(FirsthWnd, SW_SHOWDEFAULT);
::SetForegroundWindow(FirsthWnd);
FirstChildhWnd = ::GetLastActivePopup(FirsthWnd);
if (FirsthWnd != FirstChildhWnd)
::BringWindowToTop(FirstChildhWnd); // A pop-up is active so bring it to the top too.
}
else
{
Application->Initialize();
Application->Title = "YourApplicationTitle";
Application->CreateForm(__classid(TYourAppMainForm),&YourAppMainForm);
}
7/2/98 10:32:32 AM

Last Modified: 01-SEP-99