delphi – 为什么MessageBox不会在同步线程上阻塞应用程序?

据我了解并了解TThread类的方法,如果你同步你的代码,它实际上是在主应用程序线程中执行的(就像一个计时器/按钮点击等).
我一直在玩,并注意到MessageBox不会阻止主应用程序,但是睡眠就像预期的那样.这是为什么?
type
  TTestThread = class(TThread)
  private
    procedure SynchThread;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: Boolean);
  end;

procedure TTestThread.SynchThread;
begin
 MessageBoxA (0,'Hello','Test',0);
end;

procedure TTestThread.Execute;
begin
 Synchronize (SynchThread)
end;

constructor TTestThread.Create(CreateSuspended: Boolean);
begin
  inherited;
  FreeOnTerminate := True;
end;

procedure StartThread;
var
 TestThread : TTestThread;
begin
 TestThread := TTestThread.Create (FALSE);
end;

解决方法

这个答案分为两部分.

If MessageBox()/related are synchronous,why doesn’t my message loop freeze?中很好地解释了第1部分.MessageBox函数没有阻塞,它只是创建了一个带有自己的消息循环的对话框.

第2部分在MessageBox documentation中解释.

hWnd: A handle to the owner window of the message Box to be created. If this
parameter is NULL,the message Box has no owner window.

当您显示模式对话框时,Windows会禁用其所有者,但如果您为第一个参数传递0,则没有所有者,也没有禁用任何内容.因此,您的程序将在显示消息框时继续处理消息(并对其作出反应).

要更改此行为,请将表单的句柄作为第一个参数传递.例如:

procedure TTestThread.SynchThread;
begin
  MessageBoxA (Form1.Handle,0);
end;

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...