Every single developer wishes to have their client start up only a single instance of their application. This reduces the amount of possible application issues if the code makes a database connection or does some sort of processing that takes away the machine resources. The following code snippet will help Delphi programmers to keep the process count down to a single instance. This was coded using Rad Studio XE8 Delphi and is used in many of my applications.
The code will be embedded in the project’s source because it has to occur prior to the application creating the main form.
Click on the menu Project / View Source or using the project manager, you can right click and upon getting the pop-up, you can select view source as well.
You will need for the most part the following uses prior to the forms you will be setting up in the project source file.
uses
Forms,
Windows,
Dialogs,
TlHelp32,
SysUtils,
System.UITypes, ..
The function CheckProcessCount will accept the application executable name so that it can locate the process (only if it is active ). Upon locating it the result will be set to one, otherwise a zero is returned.
function CheckProcessCount(const ExeName: String): Integer;
var
NextProcessLoop: BOOL;
FHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
NextProcessLoop := Process32First(FHandle, FProcessEntry32);
Result := 0;
while Integer(NextProcessLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeName)) or
(UpperCase(FProcessEntry32.szExeFile) =UpperCase(ExeName))) then Inc(Result);
NextProcessLoop := Process32Next(FHandle, FProcessEntry32);
end;
CloseHandle(FHandle);
end;
The application executable name is sent to the processcount and will return either a 0 (not found) or a 1 (found).
If the application is already running, an informational message is given to the user and then the application handle is acquired and the window is brought to the front.
If the application is not running then the application will initialize and start running.
{$R *.RES}
Var
Handle : hwnd;
begin
if CheckProcessCount(ExtractFileName(Application.ExeName)) > 1 then
begin
MessageDlg(‘Manage-It! Adminstration Application is already running!’, mtInformation, [mbOk], 0, mbOk);
Handle := FindWindow(nil, ‘Manage-It! Help Desk Suite Administrator’);
if Handle > 0 then
begin
SetForegroundWindow(Handle);
end;
end
else
begin
Application.Title := ‘Manage-It! Administrator’;
Application.CreateForm(TAdminForm, AdminForm);
Application.Run;
end;
end.
This sample code has been compiled using Rad Studio XE8 Delphi and it does work under Windows 7 Professional. It is a Windows 32 bit application so please be aware of that.
Pretty simple but yet effective.