轉載:http://www.codefans.net/articles/332.shtml
一個程序只允許打開一次,平時見到類似的軟件比較多了,比如windows的播放器、PhotoShop等,當這些軟件打開的時候,如果需要打開他們可以打開的文件,即使你雙擊文件,也只是在已打開的軟件中運行,並不會重新打開一個進程,這樣可有效減少資源浪費。
那么實現一個程序只允許運行一個實例,方法有很多,今天主要介紹兩種方法,網上Delphi達人的辦法,希望有用:
第一種方法,使用“過程調用”:
procedure Del; // 自定義過程 var Mutex: THandle; begin Mutex := CreateMutex(nil, True, PChar(Application.Title)); if GetLastError = ERROR_ALREADY_EXISTS then begin Application.MessageBox('程序已經在運行...','系統提示', MB_ICONERROR); ReleaseMutex(Mutex); {釋放資源} Application.Terminate; end; end;
第二種方法:通過寫入dpr工程文件:
program Project1; uses Forms, windows, Unit1 in 'Unit1.pas' {Form1}; {$R *.RES} var Mutex:THandle; begin Mutex := CreateMutex(nil,true,'one'); {第3個參數任意設置} if GetLastError <> ERROR_ALREADY_EXISTS then begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end else Application.MessageBox('該程序正在運行!','提示',MB_OK); ReleaseMutex(Mutex); {釋放資源} end.
兩種方法介紹完了,任意一種方法都很好用,復制代碼到你的軟件項目中試下吧。