第二问题:
方法:
procedure LookForPreviousInstance;
var
PreviousInstanceWindow : hWnd;
AppName : array[0..30] of char;
FoundAtom : TAtom;
begin
AtomText:='OnlyOne'+Application.title;
FoundAtom := GlobalFindAtom(PChar(AtomText));
if FoundAtom <> 0 then
begin
ShowMessage('该程序已经远行了!');
StrFmt(AppName,'%s', [Application.Title]);
Application.ShowMainForm := false;
Application.Title := 'destroy me';
PreviousInstanceWindow := FindWindow(nil,AppName);
Application.Terminate;
if PreviousInstanceWindow <> 0 then
if IsIconic(PreviousInstanceWindow) then
ShowWindow(PreviousInstanceWindow,SW_RESTORE)
else SetForegroundWindow(PreviousInstanceWindow);
end;
FoundAtom := GlobalAddAtom(PChar(AtomText));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
inherited;
LookForPreviousInstance;
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
FoundAtom : TAtom;
ValueReturned : word;
begin
FoundAtom := GlobalFindAtom(Pchar(AtomText));
if FoundAtom <> 0 then ValueReturned := GlobalDeleteAtom(FoundAtom);
// inherited Destroy;
end;
方法二:
procedure TForm1.FormCreate(Sender: TObject);
begin
if GlobalFindAtom('PROGRAM_RUNNING') = 0 then
fAtom := GlobalAddAtom('PROGRAM_RUNNING')
else
begin
ShowMessage('该程序已经运行了!');
Halt;
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
GlobalDeleteAtom(fAtom);
end;
方法三:
initialization
Project:='RunOnlyOnce_MyProject';
mHandle:=CreateMutex(nil,True,PChar(Project));
if GetLastError=ERROR_ALREADY_EXISTS then
begin
ShowMessage('该程序已经运行了!');
AppName:=Application.Title;
Application.ShowMainForm:=False;
Application.Title:='destroy me';
PreviousInstanceWindow:=FindWindow(nil,PChar(AppName));
if PreviousInstanceWindow<>0 then
if IsIconic(PreviousInstanceWindow) then
ShowWindow(PreviousInstanceWindow,SW_RESTORE)
else
SetForegroundWindow(PreviousInstanceWindow);
Application.Terminate;
end;
finalization
if mHandle<>0 then
CloseHandle(mHandle);