專案源文件 (.dpr) 關鍵代碼
program Project1;
uses
Forms, Windows, Messages, SysUtils;
{$R *.res}
begin
{ 隱藏主窗體 }
if LowerCase(ParamStr(1)) = '-start' then
begin
ShowWindow(Application.Handle, SW_HIDE);
Application.ShowMainForm := False;
end;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
主窗體單元 關鍵代碼
type
TForm1 = class(TForm)
protected
procedure WndProc(var Message: TMessage); override;
end;
procedure TForm1.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_SYSCOMMAND:
case Message.WParam of
SC_CLOSE, SC_MINIMIZE:
begin
CoolTrayIcon1.MinimizeToTray := True; // 需第三方托盤組件
Application.Minimize;
end;
else
inherited;
end;
else
inherited;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
dwStyle: DWORD;
begin
{ 不在任務欄顯示 }
dwStyle := GetWindowLong(Handle, GWL_EXSTYLE);
dwStyle := dwStyle or WS_EX_TOOLWINDOW;
SetWindowLong(Application.Handle, GWL_EXSTYLE, dwStyle);
end;
關鍵點解析
ParamStr(1) 獲取第一個命令行參數,配合快捷方式或啟動腳本傳遞 -start。
ShowWindow(Application.Handle, SW_HIDE) 隱藏應用程序主窗口 (非 Form)。
Application.ShowMainForm := False 防止 Application.Run 時自動顯示。
WS_EX_TOOLWINDOW 擴展風格使窗口不出現在任務欄及 Alt+Tab。
- 攔截
WM_SYSCOMMAND 的 SC_MINIMIZE/SC_CLOSE 實現最小化到托盤而非關閉。
完整啟動腳本示例
{ 批處理啟動 }
start "" "MyApp.exe" -start
{ 或註冊表 Run 鍵 }
"MyApp.exe" -start