加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 04:09:53 所属栏目:大数据 来源:网络整理
导读:据我了解并了解TThread类的方法,如果你同步你的代码,它实际上是在主应用程序线程中执行的(就像一个计时器/按钮点击等). 我一直在玩,并注意到MessageBox不会阻止主应用程序,但是睡眠就像预期的那样.这是为什么? type TTestThread = class(TThread) private p
据我了解并了解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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读