uses
Forms,
Windows,
SysUtils,
MainForm in 'MainForm.pas' {frmMain: TfrmMain};
{$R *.RES}
var
Previous: HWND;
{This code, to allow file association and open doubleclicked file in the running instance of app
was written by Andrius Adamonis}
function EnumWindowsCallback(Handle: HWND; Param: LPARAM): Boolean; stdcall;
function IsMyClass: Boolean;
var
ClassName : array[0..30] of Char;
FormClassName: string;
begin
GetClassName(Handle, ClassName, 30);
Result := (StrIComp(ClassName, 'TfrmMain') = 0) and { this finds my window, TfrmMain }
(SendMessage(Handle, WM_FINDINSTANCE, 0, 0) = MyUniqueConst); { this checks if this is really my application }
end;
begin
Result := not IsMyClass; { needs True to continue }
if not Result { = MyClass } then Previous := Handle;
end;
var
ATOM: TAtom;
begin
Previous := 0;
ATOM := 0;
EnumWindows(@EnumWindowsCallback, 0);
if Previous <> 0 then
begin
PostMessage(Previous, WM_RESTOREAPP, 0, 0);
Exit;
end;
Application.Initialize;
Application.CreateForm(TfrmMain, frmMain);
Application.Run;
end.
procedure TfrmMain.DefaultHandler(var message);
var
S: string;
begin
with TMessage(message) do
if Msg = WM_FINDINSTANCE then
begin
Result := MyUniqueConst;
end
else inherited DefaultHandler(message);
end;
procedure TfrmMain.WMRestoreApp(var Msg: TMessage);
begin
ShowApplication;
end;
initialization
WM_FINDINSTANCE := RegisterWindowMessage('MyForm: find previous instance');
if WM_FINDINSTANCE = 0 then raise Exception.Create('Initialization failed');
begin
Application.initialation;
if CreateMutex then begin
Application.CreateForm(Form1, TForm1);
Application.Run;
end else
DestroyMutex;
end;
//主窗体文件
...
implementation
var
Mutex: hWnd;
function CreateMutex: Boolean;
var
PrevInstHandle: THandle;
AppTitle: PChar;
begin
AppTitle := StrAlloc(100);
StrPCopy(AppTitle, Application.Title);
Result := True;
Mutex := Windows.CreateMutex(nil, False, AppTitle);
if (GetLastError = ERROR_ALREADY_EXISTS) or (Mutex = 0) then begin
Result := False;
SetWindowText(Application.Handle, '');
PrevInstHandle := FindWindow(nil, AppTitle);
if PrevInstHandle <> 0 then begin
if IsIconic(PrevInstHandle) then
ShowWindow(PrevInstHandle, SW_RESTORE)
else
BringWindowToTop(PrevInstHandle);
SetForegroundWindow(PrevInstHandle);
end;
if Mutex <> 0 then
Mutex := 0;
end;
StrDispose(AppTitle);
end;
procedure DestroyMutex;
begin
if Mutex <> 0 then
CloseHandle(Mutex);
end;