轉載於網易博客:http://jiafeng26.blog.163.com/blog/static/1754251920100140134147/
windows是個多用戶多任務的操作系統,支持多個程序同時運行,如果你的程序不想讓用戶同時運行一個以上,
那應該怎樣做呢? 本文將介紹避免用戶同時運行多個程序的例子。
需要用到的函數CreateMutex ,CreateMutex 函數是windows中一個並不常用的函數,
該函數對象在系統中只能存在一個實例且是互斥體,所以利用這種特性就很簡單的實現了我們的要求。
【函數原聲明】:
function CreateMutex(lpMutexAttributes: PSecurityAttributes; bInitialOwner: BOOL; lpName: PChar): THandle;
function CreateMutex(lpMutexAttributes: PSecurityAttributes; bInitialOwner: BOOL; lpName: PChar): THandle;<br/>
【參數說明】:
lpMutexAttributes 是一個SECURITY_ATTRIBUTES 結構類型的指針,可以設置為NULL。
bInitialOwner 是否初始化互斥體。
lpName 互斥體對象的名稱。
函數返回一個互斥體句柄。
當程序運行時創建對象,如果對象已經存在就表明程序已經被運行了。。
【實現過程如下】:
新建一個工程,窗體明明為Form1.
添加一個Button按鈕命名為Button1.
雙擊按鈕添加代碼
procedure TForm1.Button1Click(Sender: TObject);
var
hw : HWND;
gt : Integer;
begin
Application.Initialize;
Application.Title := 'runmyfile';
hw := CreateMutex(nil,False,'runmyfile'); {創建互斥體對象}
gt := GetLastError;
if gt <> Error_ALREADY_EXISTS then {如果沒有發現互斥體對象}
begin
Application.CreateForm(TForm1,Form1); {創建窗體}
Application.Run;
end
else
begin
Application.MessageBox('程序已經運行','提示',MB_OK);
Application.Terminate;
ReleaseMutex(hw);{釋放互斥體}
end;
end;