danielmashman
Programmer
I am trying to implement a Delphi example I found for preventing multiple instances of an application built in c++ builder.
I have created a unit called CheckPrevious.cpp with a routine called RestoreIfRunning() and a destructor. How do I use this unit from the main project source file within WinMain()? To use the units for the forms you use the keyword USEFORM(Unit1.cpp, Form1). I know there is a USEUNIT keyword but I cannot figure out if this is what I need to use. Or do I simply include the header file CheckPrevious.h and then create an instance of the CheckPrevious class within WinMain()?
Here is the code I have created within CheckPrevious.cpp:
I have created a unit called CheckPrevious.cpp with a routine called RestoreIfRunning() and a destructor. How do I use this unit from the main project source file within WinMain()? To use the units for the forms you use the keyword USEFORM(Unit1.cpp, Form1). I know there is a USEUNIT keyword but I cannot figure out if this is what I need to use. Or do I simply include the header file CheckPrevious.h and then create an instance of the CheckPrevious class within WinMain()?
Here is the code I have created within CheckPrevious.cpp:
Code:
CheckPrevious::~CheckPrevious(void)
{
if(RemoveMe)
{
MappingHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, PChar(MappingName));
if(MappingHandle != 0)
{
InstanceInfo = MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(TInstanceInfo));
InstanceInfo.RunCOunter--;
}
else
RaiseLastOSError();
}
if(Assigned(InstanceInfo))
UnmapViewOfFile(InstanceInfo);
if(MappingHandle != 0)
CloseHandle(MappingHandle);
}
bool CheckPrevious::RestoreIfRunning(const THandle AppHandle, int MaxInstances)
{
THandle MappingHandle;
PinstanceInfo InstanceInfo;
AnsiString MappingName;
RemoveMe = true;
MappingName = StringReplace(ParamStr(0), "\", "", TReplaceFlags() << rfReplaceAll);
MappingHandle = CreateFileMapping(0xFFFFFFFF, nil, PAGE_READWRITE, 0, sizeof(TInstanceInfo), PChar(MappingName));
if(MappingHandle = 0)
RaiseLastOSError();
else
{
if(GetLastError() != ERROR_ALREADY_EXISTS) //Application not already running
{
InstanceInfo = MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(TInstanceInfo));
InstanceInfo.PreviousHandle = AppHandle;
InstanceInfo.RunCounter = 1;
return true;
}
else //application already running
{
MappingHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, PChar(MappingName));
if(MappingHandle != 0)
{
InstanceInfo = MapViewOfFile(MappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(TInstanceInfo));
if(InstanceInfo.RunCounter >= MaxInstances)
{
RemoveMe = false;
if(IsIconic(InstanceInfo.PreviousHandle))
ShowWindow(InstanceInfo.PreviousHandle, SW_RESTORE);
SetForegroundWindow(Instance.PreviousHandle);
}
else
{
InstanceInfo.PreviousHandle = AppHandle;
InstanceInfo.RunCounter++;
return false;
}
}
}
}
}