//button.onclick(sender)
h:=createMutex(nil,false,Mutex_name);
if h=0
then showmessage('创建互斥对象失败!')
else
begin
s:=getlasterror;
case s of
error_already_exists:
begin
memo1.Lines.Add('已经创建的互斥对象!');
if application.MessageBox('已经存在的互斥对象,需要删除吗?','提问',mb_yesNo+mb_iconquestion=mryes
then
begin
memo1.Lines.Add('删除创建的互斥对象');
releaseMutex(h);
closehandle(h); end;
end;
0: showmessage('操作成功')
else showmessage('异常');
end;
end;
上述代码中的红色部分在互斥对象被删除后,再次点击按钮怎么还会提示已创建的互斥对象。
h:=createMutex(nil,false,Mutex_name);
if h=0
then showmessage('创建互斥对象失败!')
else
begin
s:=getlasterror;
case s of
error_already_exists:
begin
memo1.Lines.Add('已经创建的互斥对象!');
if application.MessageBox('已经存在的互斥对象,需要删除吗?','提问',mb_yesNo+mb_iconquestion=mryes
then
begin
memo1.Lines.Add('删除创建的互斥对象');
releaseMutex(h);
closehandle(h); end;
end;
0: showmessage('操作成功')
else showmessage('异常');
end;
end;
上述代码中的红色部分在互斥对象被删除后,再次点击按钮怎么还会提示已创建的互斥对象。
也就是就,你第二次按button时h不是原来的handle,而是一个副本HANDLE
用CloseHandle来释放Mutex时,只是释放当前进程获得的副本句柄,而不会删除该Mutex内核对象。
所以会出现你的结果
var
oldh:thandle; //增加一外部变量
procedure TForm1.Button1Click(Sender: TObject);
const
Mutex_name='aaa';
var
h:thandle;
s:integer;
begin h:=createMutex(nil,false,Mutex_name);
if h=0
then showmessage('创建互斥对象失败!')
else
begin
s:=getlasterror;
case s of
error_already_exists:
begin
memo1.Lines.Add('已经创建的互斥对象!');
if application.MessageBox('已经存在的互斥对象,需要删除吗?','提问',mb_yesNo+mb_iconquestion)=mryes
then
begin
memo1.Lines.Add('删除创建的互斥对象');
releaseMutex(h);
closehandle(h);
closehandle(oldh); //这个必须 end;
end;
0: begin
showmessage('操作成功');
oldh:=h; // 增加这个
end;
else showmessage('异常');
end;
end;end;