Mostrando tela de “aguarde” para processos demorados – Show Delphi

DICAS

Visite a biblioteca de dicas da comunidade.

Saiba mais

ARTIGOS

Abordagens detalhadas sobre assuntos diversos.

Saiba mais

INICIANTES

Aprenda a programar de um modo simples e fácil.

Saiba mais

DOWNLOADS

Acesse os materiais exclusivos aos membros.

Saiba mais
voltar

PARA QUEM GOSTA DE DELPHI

Mostrando tela de “aguarde” para processos demorados

 

Pesquisando a respeito encontrei em um post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
unit Unit1;
 
interface
 
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
 
type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Shape1: TShape;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.Button1Click(Sender: TObject);
var
  F: TForm;
  MSG: Tlabel;
  Borda: TShape;
begin
  F := TForm.Create(Application);
  F.BorderStyle := bsNone;
  F.Position := poDesktopCenter;
  F.Width := 100;
  F.Height := 16; // até aqui criamos o form
 
  Borda := TShape.Create(Application);
  Borda.Parent := F;
  Borda.Align := alClient; // uma borda envolta do form
 
  MSG := Tlabel.Create(Application);
  MSG.Parent := F;
  MSG.Transparent := true;
  MSG.AutoSize := false;
  MSG.Width := 98;
  MSG.Caption := 'Aguarde';
  MSG.Alignment := taCenter; // label com a mensagem "Aguarde"
 
  F.Show;
  F.Update;
 
  // Aqui você coloca os procedimentos desejados
  Sleep(5000);   // exemplo de processamento, aguarda 5 segundos
 
  F.Free; // E finalmente libera a janela
end;
 
end.

Fonte base: http://www.planetadelphi.com.br/dica/5074/mostrando-tela-de-%22aguarde-%22

Posteriormente, Ivan Cezar, membro da comunidade disponibilizou uma unit para
trabalhar facilmente com telas de “Aguarde”.

Eis o código fonte da Unit do Ivan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
{ *************************************************************************************
  Unit para criar uma telade aguarde modal, enquanto o processamento segue sem interrupção
  Desenvolvido por
  ** Ivan Cesar  - ivancesarf@gmail.com Skype: proadvanced **
  Esta unit é disponibilizada como está, não existe nehuma responsabilidade de suporte
  Use por sua conta e risco
  Pode ser utilizada e alterada a vontade, desde que mantidos os créditos originais
  Caso implemente alguma melhoria, peço por gentileza que me disponibilize as alterações
  ************************************************************************************** }
unit Util.Dialog;
 
interface
 
uses
  Classes,
  Forms,
  Dialogs,
  StdCtrls,
  Windows,
  ExtCtrls,
  Math,
  StrUtils,
  Controls,
  SysUtils,
  ComCtrls,
  Graphics,
  Messages,
  UITypes,
  AppEvnts,
  Types;
 
type
  TMsgDlgType    = (mtWarning, mtError, mtInformation, mtConfirmation, mtCustom);
  TMsgDlgBtn     = (mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp, mbClose);
  TMsgDlgButtons = set of TMsgDlgBtn;
 
procedure MessageBoxError(const Msg: string);
function MessageBoxYesNo(const Msg: string): Integer;
function MessageBoxYesNoCancel(const Msg: string): Integer;
procedure MessageBoxInformation(const Msg: string);
function MessageBox(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
 
procedure WaitShowMessage(const Msg: string = 'Processando solicitação ...');
procedure WaitShowProgress(const Msg: string = 'Processando solicitação ...'; ExecProc: TProc = nil); overload;
procedure WaitShowProgress(const Msg: string = 'Processando solicitação ...'; ExecFunc: TFunc<Boolean> = nil); overload;
procedure WaitCloseMessage;
 
implementation
 
resourcestring
  SMsgDlgWarning = 'Atenção';
  SMsgDlgError = 'Erro';
  SMsgDlgInformation = 'Informação';
  SMsgDlgConfirm = 'Confirme';
  SMsgDlgYes = '&Sim';
  SMsgDlgNo = '&Não';
  SMsgDlgOK = 'OK';
  SMsgDlgCancel = 'Cancelar';
  SMsgDlgAbort = '&Abortar';
  SMsgDlgRetry = '&Repetir';
  SMsgDlgIgnore = '&Ignorar';
  SMsgDlgAll = '&Todos';
  SMsgDlgNoToAll = 'Nã&o à todos';
  SMsgDlgYesToAll = 'Si&m à todos';
  SMsgDlgHelp = 'Aj&uda';
  SMsgDlgClose = '&Fechar';
  SMsgDlgCopyToClipBrd = 'Copiar mensagem';
  SHintMsgDlgCopyToClipBrd = 'Copia a mensagem para a área de transferência';
 
var
  Captions: array [TMsgDlgType] of Pointer = (
    @SMsgDlgWarning,
    @SMsgDlgError,
    @SMsgDlgInformation,
    @SMsgDlgConfirm,
    nil
  );
 
  IconIDs: array [TMsgDlgType] of PChar = (
    IDI_EXCLAMATION,
    IDI_HAND,
    IDI_ASTERISK,
    IDI_QUESTION,
    nil
  );
 
  ButtonCaptions: array [TMsgDlgBtn] of Pointer = (
    @SMsgDlgYes,
    @SMsgDlgNo,
    @SMsgDlgOK,
    @SMsgDlgCancel,
    @SMsgDlgAbort,
    @SMsgDlgRetry,
    @SMsgDlgIgnore,
    @SMsgDlgAll,
    @SMsgDlgNoToAll,
    @SMsgDlgYesToAll,
    @SMsgDlgHelp,
    @SMsgDlgClose
  );
 
  ButtonNames: array [TMsgDlgBtn] of string = (
    'Yes',
    'No',
    'OK',
    'Cancel',
    'Abort',
    'Retry',
    'Ignore',
    'All',
    'NoToAll',
    'YesToAll',
    'Help',
    'Close'
  );
 
  ModalResults: array [TMsgDlgBtn] of Integer = (
    mrYes,
    mrNo,
    mrOk,
    mrCancel,
    mrAbort,
    mrRetry,
    mrIgnore,
    mrAll,
    mrNoToAll,
    mrYesToAll,
    0,
    mrClose
  );
 
  ButtonWidths: array [TMsgDlgBtn] of Integer; // inicializa com zero
 
type
  TMessageForm = class(TForm)
  private
    RichEditMessage: TRichEdit;
    procedure HelpButtonClick(Sender: TObject);
  protected
    procedure CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure CustomEnter(Sender: TObject);
    procedure CutomLabelClick(Sender: TObject);
    procedure CustomWriteTextToClipBoard;
  public
    constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
  end;
 
type
  TWaitForm = class(TForm)
  private
    PanelContainer: TPanel;
    LabelMessage  : TLabel;
    AppEvents     : TApplicationEvents;
  protected
    procedure CustomCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure CustomAppEventsModalBegin(Sender: TObject);
  end;
 
  { TMessageForm }
 
var
  FExeVErsion: string;
 
constructor TMessageForm.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
  inherited CreateNew(AOwner, Dummy);
  Font.Assign(Screen.MessageFont);
end;
 
procedure TMessageForm.CustomEnter(Sender: TObject);
begin
  if Sender = RichEditMessage then
    Perform($0028, 0, 0);
end;
 
procedure TMessageForm.CustomKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if (Shift = [ssCtrl]) and (Key = Word('C')) then
  begin
    MessageBeep(0);
    CustomWriteTextToClipBoard;
  end;
end;
 
procedure TMessageForm.CustomWriteTextToClipBoard;
var
  FData   : THandle;
  FDataPtr: Pointer;
  FText   : string;
begin
  if OpenClipBoard(0) then
  begin
    if FExeVErsion.Trim.IsEmpty then
      FText := Caption + sLineBreak + Trim(RichEditMessage.Text)
    else
      FText := Caption + ' - ' + FExeVErsion + sLineBreak + Trim(RichEditMessage.Text);
    try
      FData := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, ByteLength(FText) + SizeOf(WideChar));
      try
        FDataPtr := GlobalLock(FData);
        try
          Move(PWChar(FText)^, FDataPtr^, ByteLength(FText) + SizeOf(WideChar));
          EmptyClipBoard;
          SetClipboardData(CF_UNICODETEXT, FData);
        finally
          GlobalUnlock(FData);
        end;
      except
        GlobalFree(FData);
        raise;
      end;
    finally
      CloseClipBoard;
    end;
  end
  else
    raise Exception.Create('Não foi possível acessar a área de transferência.');
end;
 
procedure TMessageForm.CutomLabelClick(Sender: TObject);
begin
  MessageBeep(0);
  CustomWriteTextToClipBoard;
end;
 
procedure TMessageForm.HelpButtonClick(Sender: TObject);
begin
  if HelpContext <> 0 then
    Application.HelpContext(HelpContext);
end;
 
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
  I     : Integer;
  Buffer: array [0 .. 51] of Char;
begin
  for I := 0 to 25 do
    Buffer[I] := Chr(I + Ord('A'));
  for I := 0 to 25 do
    Buffer[I + 26] := Chr(I + Ord('a'));
  GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
  Result.X := Result.X div 52;
end;
 
function TaskBarBounds: TRect;
begin
  GetWindowRect(FindWindow('Shell_TrayWnd', nil), Result);
end;
 
function TaskBarPosition: TAlign;
var
  TaskBar   : TRect;
  ScrW, ScrH: Integer;
begin
  ScrW := Screen.Width;
  ScrH := Screen.Height;
  TaskBar := TaskBarBounds;
  if (TaskBar.Top > ScrH div 2) and (TaskBar.Right >= ScrW) then
    Result := alBottom
  else
    if (TaskBar.Top < ScrH div 2) and (TaskBar.Bottom <= ScrW div 2) then
    Result := alTop
  else
    if (TaskBar.Left < ScrW div 2) and (TaskBar.Top <= 0) then
    Result := alLeft
  else
    Result := alRight;
end;
 
function TaskBarWidth: Integer;
begin
  with TaskBarBounds do
    Result := Right - Left;
end;
 
function TaskBarHeight: Integer;
begin
  with TaskBarBounds do
    Result := Bottom - Top;
end;
 
function GetExeVersion: string;
type
  pFFI = ^VS_FIXEDFILEINFO;
var
  F               : pFFI;
  dwHandle, dwLen : DWORD;
  szInfo          : LongInt;
  pchData, pchFile: PChar;
  ptrBuff         : Pointer;
  strFile         : string;
begin
  strFile := Application.ExeName;
  pchFile := StrAlloc(Length(strFile) + 1);
  StrPcopy(pchFile, strFile);
  szInfo := GetFileVersionInfoSize(pchFile, dwHandle);
  Result := '';
  if szInfo > 0 then
  begin
    pchData := StrAlloc(szInfo + 1);
    if GetFileVersionInfo(pchFile, dwHandle, szInfo, pchData) then
    begin
      VerQueryValue(pchData, '\', ptrBuff, dwLen);
      F := pFFI(ptrBuff);
      Result := Format('v%d.%d.%d (%.3d) %s', [
        HiWord(F^.dwFileVersionMs),
        LoWord(F^.dwFileVersionMs),
        HiWord(F^.dwFileVersionLs),
        LoWord(F^.dwFileVersionLs),
{$IFDEF DEBUG}'Debug'{$ELSE}''{$ENDIF}]).Trim;
    end;
    StrDispose(pchData);
  end;
  StrDispose(pchFile);
end;
 
function CreateMessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): TForm;
const
  mcHorzMargin    = 8;
  mcVertMargin    = 8;
  mcHorzSpacing   = 10;
  mcVertSpacing   = 10;
  mcButtonWidth   = 50;
  mcButtonHeight  = 14;
  mcButtonSpacing = 4;
  DrawFormatLine  = DT_CALCRECT or DT_LEFT or DT_SINGLELINE;
  DrawFormatText  = DT_EXPANDTABS or DT_CALCRECT or DT_WORDBREAK;
var
  DialogUnits     : TPoint;
  HorzMargin      : Integer;
  VertMargin      : Integer;
  HorzSpacing     : Integer;
  VertSpacing     : Integer;
  ButtonTop       : Integer;
  ButtonWidth     : Integer;
  ButtonHeight    : Integer;
  ButtonSpacing   : Integer;
  ButtonCount     : Integer;
  ButtonGroupWidth: Integer;
  MessageWidth    : Integer;
  MessageHeight   : Integer;
  LabelWidth      : Integer;
  ScreenWidth     : Integer;
  ScreenHeight    : Integer;
  X               : Integer;
  L               : Integer;
  B, CancelButton : TMsgDlgBtn;
  IconID          : PChar;
  TextRect        : TRect;
  LButton         : TButton;
  LMsg            : string;
begin
  LMsg := Trim(Msg);
 
  Result := TMessageForm.CreateNew(Application);
  with Result do
  begin
    Font := Application.DefaultFont;
    BiDiMode := Application.BiDiMode;
    BorderStyle := bsDialog;
    Canvas.Font := Font;
    KeyPreview := True;
    ShowHint := True;
    PopupMode := pmAuto;
    Position := poScreenCenter;
    OnKeyDown := TMessageForm(Result).CustomKeyDown;
    // definicao das variaveis
    DialogUnits := GetAveCharSize(Canvas);
    HorzMargin := MulDiv(mcHorzMargin, DialogUnits.X, 4);
    VertMargin := MulDiv(mcVertMargin, DialogUnits.Y, 8);
    HorzSpacing := MulDiv(mcHorzSpacing, DialogUnits.X, 4);
    VertSpacing := MulDiv(mcVertSpacing, DialogUnits.Y, 8);
    ButtonWidth := MulDiv(mcButtonWidth, DialogUnits.X, 4);
    ButtonHeight := MulDiv(mcButtonHeight, DialogUnits.Y, 8);
    ButtonSpacing := MulDiv(mcButtonSpacing, DialogUnits.X, 4);
    // tamanho do grupo de botoes
    for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
    begin
      if B in Buttons then
      begin
        if ButtonWidths[B] = 0 then
        begin
          TextRect := Rect(0, 0, 0, 0);
          DrawText(Canvas.Handle, PChar(LoadResString(ButtonCaptions[B])), -1, TextRect,
            DrawFormatLine or DrawTextBiDiModeFlagsReadingOnly);
          with TextRect do
            ButtonWidths[B] := Right - Left + 8;
        end;
        if ButtonWidths[B] > ButtonWidth then
          ButtonWidth := ButtonWidths[B];
      end;
    end;
    // tamanho do label
    TextRect := Rect(0, 0, 0, 0);
    DrawText(Canvas.Handle, SMsgDlgCopyToClipBrd, -1, TextRect, DrawFormatLine or DrawTextBiDiModeFlagsReadingOnly);
    LabelWidth := TextRect.Right - TextRect.Left + 8;
    SetRect(TextRect, 0, 0, Screen.WorkAreaWidth + 1 div 2, 0);
    // tamanho da mensagem
    DrawText(Canvas.Handle, LMsg, Length(LMsg) + 1, TextRect, DrawFormatText or DrawTextBiDiModeFlagsReadingOnly);
    MessageWidth := TextRect.Right;
    MessageHeight := TextRect.Bottom;
    // ícone
    IconID := IconIDs[DlgType];
    if IconID <> nil then
    begin
      Inc(MessageWidth, 32 + HorzSpacing);
      if MessageHeight < 32 then
        MessageHeight := 32;
    end;
    ButtonCount := 0;
    for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
      if B in Buttons then
        Inc(ButtonCount);
 
    ButtonGroupWidth := 0;
    if ButtonCount > 0 then
      ButtonGroupWidth := (ButtonWidth * ButtonCount + ButtonSpacing * (ButtonCount - 1));
 
    // tamanho da tela
    ScreenWidth := Screen.WorkAreaWidth;
    ScreenHeight := Screen.WorkAreaHeight;
    case TaskBarPosition of
      alTop, alBottom:
        ScreenHeight := ScreenHeight - TaskBarHeight;
      alLeft, alRight:
        ScreenWidth := ScreenWidth - TaskBarWidth;
    end;
 
    // tamanho do formulario
    ClientWidth := Max(MessageWidth + 20, ButtonGroupWidth + LabelWidth) + HorzMargin * 2;
    if ClientWidth > ScreenWidth then
    begin
      ClientWidth := ScreenWidth;
      if ClientWidth < (ButtonGroupWidth + LabelWidth) then
        AutoScroll := True;
    end;
    ClientHeight := MessageHeight + ButtonHeight + VertSpacing + VertMargin * 2;
    if ClientHeight > ScreenHeight then
      ClientHeight := ScreenHeight;
 
    // titulo
    Caption := Application.Title;
 
    { if DlgType <> mtCustom then
      Caption := Caption + '   -   ' + LoadResString(Captions[DlgType]); }
 
    FExeVErsion := GetExeVersion;
 
    // criacao da imagem
    if IconID <> nil then
      with TImage.Create(Result) do
      begin
        Name := 'Image';
        Parent := Result;
        Transparent := True;
        IncrementalDisplay := True;
        Picture.Icon.Handle := LoadIcon(0, IconID);
        SetBounds(HorzMargin, VertMargin, 32, 32);
      end;
 
    // criacao do richedit
    TMessageForm(Result).RichEditMessage := TRichEdit.Create(Result);
    with TMessageForm(Result).RichEditMessage do
    begin
      Name := 'RichMessage';
      Parent := Result;
      Cursor := crArrow;
      WordWrap := True;
      BevelInner := bvNone;
      BevelOuter := bvNone;
      BorderStyle := bsNone;
      ParentColor := True;
      PlainText := True;
      ScrollBars := TScrollStyle.ssVertical;
      Lines.Text := LMsg;
      ReadOnly := True;
      BoundsRect := TextRect;
      BiDiMode := Result.BiDiMode;
      TabStop := False;
      OnEnter := TMessageForm(Result).CustomEnter;
      L := MessageWidth - TextRect.Right + HorzMargin;
      if UseRightToLeftAlignment then
        L := Result.ClientWidth - L - Width;
      SetBounds(L, VertMargin, Result.ClientWidth - 65, Result.ClientHeight - (ButtonHeight + VertMargin + VertSpacing));
    end;
 
    // definicao dos botoes
    if mbCancel in Buttons then
      CancelButton := mbCancel
    else
      if mbNo in Buttons then
      CancelButton := mbNo
    else
      CancelButton := mbOK;
 
    // posicao Top dos botoes
    ButtonTop := Result.Height - (ButtonHeight + VertMargin + VertSpacing + 10);
 
    // criacao do label
    with TLabel.Create(Result) do
    begin
      Name := 'LabelClpBrd';
      Parent := Result;
      AutoSize := True;
      Transparent := True;
      Layout := tlCenter;
      Font.Style := [fsUnderline, fsItalic];
      Font.Size := 7;
      Cursor := crHandPoint;
      Caption := SMsgDlgCopyToClipBrd;
      Hint := SHintMsgDlgCopyToClipBrd;
      OnClick := TMessageForm(Result).CutomLabelClick;
      SetBounds(mcHorzSpacing, ButtonTop + (ButtonHeight div 2) - mcVertMargin, LabelWidth, 15);
    end;
 
    // posicao incial do grupo de botoes
    X := (ClientWidth - ButtonGroupWidth + LabelWidth) div 2;
 
    // criacao dos botoes
    for B := Low(TMsgDlgBtn) to High(TMsgDlgBtn) do
      if B in Buttons then
      begin
        LButton := TButton.Create(Result);
        with LButton do
        begin
          Name := ButtonNames[B];
          Parent := Result;
          Caption := LoadResString(ButtonCaptions[B]);
          ModalResult := ModalResults[B];
          if B = DefaultButton then
          begin
            Default := True;
            ActiveControl := LButton;
          end;
          if B = CancelButton then
            Cancel := True;
          SetBounds(X, ButtonTop, ButtonWidth, ButtonHeight);
          Inc(X, ButtonWidth + ButtonSpacing);
          if B = mbHelp then
            OnClick := TMessageForm(Result).HelpButtonClick;
        end;
      end;
  end;
  WaitCloseMessage;
end;
 
procedure ShowMsg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn);
begin
  with CreateMessageDlg(Msg, DlgType, Buttons, DefaultButton) do
  begin
    ShowModal;
    Free;
  end;
end;
 
function QueryMsg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
begin
  with CreateMessageDlg(Msg, DlgType, Buttons, DefaultButton) do
  begin
    try
      ShowModal;
      Result := ModalResult;
    finally
      Free;
    end;
  end;
end;
 
procedure MessageBoxError(const Msg: string);
begin
  MessageBeep(16);
  ShowMsg(Msg, mtError, [mbOK], mbOK);
end;
 
function MessageBoxYesNo(const Msg: string): Integer;
begin
  MessageBeep(16);
  Exit(QueryMsg(Msg, mtConfirmation, [mbYes, mbNo], mbNo));
end;
 
function MessageBoxYesNoCancel(const Msg: string): Integer;
begin
  MessageBeep(16);
  Exit(QueryMsg(Msg, mtConfirmation, [mbYes, mbNo, mbCancel], mbCancel));
end;
 
procedure MessageBoxInformation(const Msg: string);
begin
  MessageBeep(64);
  ShowMsg(Msg, mtInformation, [mbOK], mbOK);
end;
 
function MessageBox(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; DefaultButton: TMsgDlgBtn): Integer;
begin
  Exit(QueryMsg(Msg, DlgType, Buttons, DefaultButton));
end;
 
{ TWaitForm }
 
procedure TWaitForm.CustomAppEventsModalBegin(Sender: TObject);
begin
  WaitCloseMessage;
end;
 
procedure TWaitForm.CustomCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  // método para implementação futura, onde poderá ser cancelada uma ação demorada
  CanClose := True;
end;
 
procedure DisableProcessWindowsGhosting;
var
  User32: HMODULE;
  Proc  : TProcedure;
begin
  User32 := GetModuleHandle('USER32');
  if User32 <> 0 then
  begin
    Proc := GetProcAddress(User32, 'DisableProcessWindowsGhosting');
    if Assigned(Proc) then
      Proc;
  end;
end;
 
procedure EmptyKeyQueue;
var
  Msg: TMsg;
begin
  while PeekMessage(Msg, 0, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE or PM_NOYIELD) do;
end;
 
procedure EmptyMouseQueue;
var
  Msg: TMsg;
begin
  while PeekMessage(Msg, 0, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE or PM_NOYIELD) do;
end;
 
var
  WaitForm      : TForm;
  LastActiveForm: TForm;
  WindowList    : TTaskWindowList;
  WindowLocked  : Boolean;
 
const
  MinHeight = 120;
  MinWidth  = 450;
 
function CreateWaitDlg(const Msg: string): TForm;
const
  FWhiteColor = 16777215;
  FFontTahoma = 'Tahoma';
 
var
  FPanelLeft, FPanelTop: Integer;
begin
  if not Assigned(LastActiveForm) then
    if Assigned(Screen.ActiveForm) then
      if not(Screen.ActiveForm.ClassNameIs(TWaitForm.ClassName)) then
      begin
        LastActiveForm := Screen.ActiveForm;
        if LastActiveForm.FormStyle = fsMDIChild then
          LastActiveForm := Application.MainForm;
        if Assigned(LastActiveForm) then
          WindowLocked := LockWindowUpdate(LastActiveForm.Handle);
      end;
 
  Result := TWaitForm.CreateNew(LastActiveForm);
  with Result do
  begin
    Name := 'WaitForm';
    BorderIcons := [];
    BorderStyle := bsNone;
    DoubleBuffered := False;
    Color := clFuchsia;
    Tag := -99;
    PopupMode := pmAuto;
    OnCloseQuery := TWaitForm(Result).CustomCloseQuery;
    Position := poOwnerFormCenter;
    Caption := Application.Title;
    // dimensões padrao
    ClientHeight := MinHeight;
    ClientWidth := MinWidth;
    // dimensiona de acordo ao formulario ativo
    if Assigned(LastActiveForm) then
    begin
      ClientHeight := LastActiveForm.Height;
      ClientWidth := LastActiveForm.Width;
    end;
    // posição do panel
    FPanelLeft := 0;
    FPanelTop := (ClientHeight div 2) - (MinHeight div 2);
    // tratamento de transparência
    TransparentColorValue := Color;
    TransparentColor := True;
    AlphaBlendValue := 240;
    AlphaBlend := True;
  end;
 
  // panel
  TWaitForm(Result).PanelContainer := TPanel.Create(Result);
  with TWaitForm(Result).PanelContainer do
  begin
    Parent := Result;
    Color := $00804000; // $0068001F;
    ParentBackground := False;
    if Assigned(LastActiveForm) then
      BevelKind := bkNone
    else
      BevelKind := bkFlat;
    SetBounds(FPanelLeft, FPanelTop, TWaitForm(Result).ClientWidth, MinHeight);
  end;
 
  // label version
  with TLabel.Create(Result) do
  begin
    Parent := TWaitForm(Result).PanelContainer;
    Transparent := True;
    Caption := GetExeVersion;
    ParentFont := False;
    Layout := tlCenter;
    Font.Color := FWhiteColor;
    Font.Name := FFontTahoma;
    Font.Size := 7;
    Left := 8;
    Top := 5;
  end;
 
  // label aguarde
  with TLabel.Create(Result) do
  begin
    Parent := TWaitForm(Result).PanelContainer;
    AlignWithMargins := True;
    Align := alTop;
    Margins.Top := 15;
    Alignment := taCenter;
    Transparent := True;
    Caption := 'Aguarde';
    ParentFont := False;
    Layout := tlCenter;
    Font.Color := FWhiteColor;
    Font.Name := FFontTahoma;
    Font.Size := 18;
    Font.Style := [fsBold];
  end;
 
  // label msg
  TWaitForm(Result).LabelMessage := TLabel.Create(Result);
  with TWaitForm(Result).LabelMessage do
  begin
    Parent := TWaitForm(Result).PanelContainer;
    AlignWithMargins := True;
    Align := alClient;
    Alignment := taCenter;
    Transparent := True;
    Caption := 'Processando ...';
    ParentFont := False;
    Layout := tlCenter;
    WordWrap := True;
    Font.Color := FWhiteColor;
    Font.Name := FFontTahoma;
    Font.Size := 12;
    Font.Style := [fsBold];
  end;
 
  // ApplicationEvents
  TWaitForm(Result).AppEvents := TApplicationEvents.Create(Result);
  with TWaitForm(Result).AppEvents do
    OnModalBegin := TWaitForm(Result).CustomAppEventsModalBegin;
end;
 
procedure WaitShowMessage(const Msg: string);
begin
  if not Assigned(WaitForm) then
  begin
    WaitForm := CreateWaitDlg(Msg);
    with WaitForm do
    begin
      WindowList := DisableTaskWindows(0);
      Screen.FocusedForm := WaitForm;
      Show;
      SendMessage(Handle, CM_ACTIVATE, 0, 0);
      Screen.Cursor := crHourGlass;
    end;
  end;
 
  with TWaitForm(WaitForm) do
  begin
    if Trim(Msg) = '' then
      LabelMessage.Caption := 'Processando ...'
    else
      LabelMessage.Caption := Trim(Msg);
  end;
  Application.ProcessMessages;
end;
 
procedure WaitCloseMessage;
begin
  try
    if Assigned(WaitForm) then
    begin
      try
        if WindowList <> nil then
          EnableTaskWindows(WindowList);
 
        WaitForm.Tag := -1;
        WaitForm.Close;
        FreeAndNil(WaitForm);
      finally
        EmptyKeyQueue;
        EmptyMouseQueue;
        LastActiveForm := nil;
        WindowList := nil;
        Screen.Cursor := crDefault;
      end;
    end;
  finally
    if WindowLocked then
    begin
      LockWindowUpdate(0);
      WindowLocked := False;
    end;
  end;
end;
 
procedure WaitShowProgress(const Msg: string; ExecProc: TProc);
begin
  WaitShowMessage(Msg);
  try
    if Assigned(ExecProc) then
      ExecProc;
  finally
    WaitCloseMessage;
  end;
end;
 
procedure WaitShowProgress(const Msg: string; ExecFunc: TFunc<Boolean>);
begin
  WaitShowMessage(Msg);
  try
    if Assigned(ExecFunc) then
      ExecFunc;
  finally
    WaitCloseMessage;
  end;
end;
 
initialization
 
DisableProcessWindowsGhosting;
 
end.

Exemplos de uso da Unit do Ivan

Processando uma rotina

1
2
3
4
5
6
7
8
9
procedure TForm1.Button1Click(Sender: TObject);
begin
  WaitShowProgress('Processando ...',
 
    procedure
    begin
      // codigo
    end);
end;

Executando algum código

1
2
3
4
5
6
7
8
9
10
procedure TForm1.Button1Click(Sender: TObject);
begin
  WaitShowMessage('Processando ...');
 
  try
    // seu codigo
  finally
    WaitCloseMessage;
  end;
end;

Você pode contribuir com a melhoria destes métodos pelos comentários do post.

Facebook Comments

Posts Relacionados

  • Giovani Da Cruz
  • 336 views
  • 1 comentários
  • 24 de novembro de 2016

Uma resposta para “Mostrando tela de “aguarde” para processos demorados”

  1. kledson disse:

    Muito Obrigado pela dica.

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Ir ao topo

© 2016 Infus Soluções em Tecnologia - Todos os Direitos Reservados