你需要做的有點不同。首先你需要檢查表單何時最小化。這可能通過捕捉消息WM_SIZE
procedure WMSize(var Msg: TMessage); message WM_SIZE;
然後進行:
procedure TForm1.WMSize(var Msg: TMessage);
begin
if Msg.WParam = SIZE_MINIMIZED then ....
end;
通常你也想關閉按鈕,以儘量減少應用程序。這可以通過實施一個CloseQuery事件來實現。
我給你做了一個基於你自己的代碼的小例子。
首先DFM代碼:
object Form11: TForm11
Left = 0
Top = 0
Caption = 'Form11'
ClientHeight = 299
ClientWidth = 635
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCloseQuery = FormCloseQuery
OnCreate = FormCreate
OnHide = FormHide
PixelsPerInch = 96
TextHeight = 13
object TrayIcon1: TTrayIcon
OnDblClick = TrayIcon1DblClick
Left = 312
Top = 152
end
object PopupMenu1: TPopupMenu
Left = 184
Top = 112
object Close1: TMenuItem
Caption = 'Close'
Default = True
OnClick = Close1Click
end
end
end
然後實際的源代碼:
unit Unit11;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus;
type
TForm11 = class(TForm)
TrayIcon1: TTrayIcon;
PopupMenu1: TPopupMenu;
Close1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Close1Click(Sender: TObject);
procedure TrayIcon1DblClick(Sender: TObject);
private
AllowClose: Boolean;
public
procedure WMSize(var Msg: TMessage); message WM_SIZE;
end;
var
Form11: TForm11;
implementation
{$R *.dfm}
procedure TForm11.Close1Click(Sender: TObject);
begin
AllowClose := True;
Close;
end;
procedure TForm11.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := AllowClose;
if not AllowClose then
Hide;
end;
procedure TForm11.FormCreate(Sender: TObject);
begin
AllowClose := false;
TrayIcon1.Hint := 'Hint';
TrayIcon1.AnimateInterval := 200;
TrayIcon1.BalloonTitle := 'Hint';
TrayIcon1.BalloonHint := 'Double click to restore Application';
TrayIcon1.BalloonFlags := bfInfo;
end;
procedure TForm11.FormHide(Sender: TObject);
begin
TrayIcon1.Visible := True;
TrayIcon1.Animate := True;
TrayIcon1.ShowBalloonHint;
end;
procedure TForm11.TrayIcon1DblClick(Sender: TObject);
begin
TrayIcon1.Visible := false;
Show();
WindowState := wsNormal;
Application.BringToFront();
end;
procedure TForm11.WMSize(var Msg: TMessage);
begin
if Msg.WParam = SIZE_MINIMIZED then
Close;
end;
end.
爲什麼要改變'WindowState'?這足以隱藏主窗體 –
我只是用它來確保「MainForm」已被最小化 –
你隱藏了主窗體。這就是從任務欄中刪除按鈕。最小化隱藏表單毫無意義。這樣做意味着您忘記了表單是正常化還是最大化還是最小化。 –