카테고리 없음

[시스템] 일정시간 경과후 없어지는 MessageBox

쇼핑스크래퍼3 2023. 9. 13. 07:15
unit Unit1;

interface

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

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

  TForm1 = class(TForm)
    Button1: TButton;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    FMboxThread: TMBoxThread;
    FWinHandle: HWnd;
  end;

var
  Form1: TForm1;
  CreatedBox: Boolean;

implementation
{$R *.DFM}

constructor TMboxThread.Create;
begin
  // thread의 실행이 종료하면 자동으로 free되게 설정
  FreeOnTerminate := True;

  inherited Create(False);
end;

procedure TMboxThread.Execute;
begin
  MessageBox(Application.Handle, '이 메시지박스는 자동으로 없어집니다', '알림',
             MB_APPLMODAL + MB_SETFOREGROUND);
  CreatedBox := False;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CreatedBox := False;
  Timer1.Interval := 3000;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  FMBoxThread    := TMBoxThread.Create;
  CreatedBox     := True;
  Timer1.Enabled := True;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := False;
  if Assigned(FMBoxThread) and CreatedBox then
  begin
    // MessageBox 의 핸들을 찾아서 종료시킨다
    FWinHandle := GetForegroundWindow;
    SendMessage(FWinHandle, WM_CLOSE, 0, 0);
  end;
end;

end.