2007. február 17., szombat

How can I close a MessageBox()


Problem/Question/Abstract:

How can I close a MessageBox()

Answer:

You can use a thread to achieve that:

unit MsgThread;

interface

uses
  Windows, Messages, SysUtils, Classes, Controls, Forms, StdCtrls, ExtCtrls;

type
  TMboxThread = class(TThread)
  private
    { private declarations }
  protected
    procedure Execute; override;
  public
    constructor Create;
  end;

type
  TFrmMsgThread = class(TForm)
    BtnClose: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Timer1: TTimer;
    procedure BtnCloseClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
  private
    FFirst: boolean;
    FMboxThread: TMBoxThread;
    FWinHandle: HWnd;
  public
    { public declarations }
  end;

var
  FrmMsgThread: TFrmMsgThread;

implementation

{$R *.DFM}

{ TMboxThread }

constructor TMboxThread.Create;
begin
  FreeOnTerminate := True;
  inherited Create(False);
end;

procedure TMboxThread.Execute;
begin
  { Place thread code here }
  MessageBox(Application.Handle, 'Text', 'Caption',
    MB_APPLMODAL + MB_SETFOREGROUND);
end;

{ TForm1 }

procedure TFrmMsgThread.BtnCloseClick(Sender: TObject);
begin
  FMBoxThread := TMBoxThread.Create;
  FFirst := true;
  Timer1.Enabled := true;
end;

procedure TFrmMsgThread.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := false;
  if FFirst then
  begin
    FWinHandle := GetForegroundWindow;
    FFirst := false;
    Timer1.Enabled := true;
  end
  else
    SendMessage(FWinHandle, WM_CLOSE, 0, 0);
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése