我用了一种使用原子(atom)+互斥(Mutex)+FindWindow的方法可以是程序只
运行一次,并且将应用程序调入前台。若您的应用程序注册为缺省打开为某种
扩展名文件的程序,将打开您所双击的文件,并且前台运行。
在我的一个MDI程序下通过了。
在dpr文件中:
var
hMutex : Thandle;
WaitResult : word;
Mf : DWORD;
S:String;
begin
hMutex := createMutex(nil,false,pchar(utCommon.SysName));
WaitResult := WaitForSingleObject(hMutex,10);
if ( waitResult = WAIT_TIMEOUT ) then
begin
S:=ParamStr(1);//实际上是您所双击的文件名(含路径)
Mf:=FindWindow('TMainForm', ‘主窗口的Caption');
if (Mf<>0) and (GlobalFindAtom(PChar(S))=0) then
begin
SendMessage(Mf, WM_User+1, GlobalAddAtom(PChar(S)), Length(S)+1);
WaitForSingleObject(hMutex,10);
end;
SetForegroundWindow (Mf);
end
else
begin
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
Application.Run;
ReleaseMutex(hMutex);
end;
CloseHandle(hMutex); // close the mutex handle
end.
主窗口:
procedure TMainForm.WndProc(var Message: TMessage);
begin
if Message.Msg=WM_User+1 then
begin
FillChar(OpenFileName, Sizeof(OpenFileName),0);
GlobalGetAtomName(Message.WParam, @OpenFileName, Message.LParam);
Show;
WindowState := wsMaximized;
Application.BringToFront;
OpenTest(OpenFileName); //打开一个子窗口显示文件
GlobalDeleteAtom(Message.WParam);
end
else
Inherited WndProc(Message);
end;