如何将控制台应用程序隐藏到托盘中?

问题描述 投票:0回答:1

我希望我的控制台应用程序在启动后隐藏在系统托盘中。在使用 GUI 应用程序时,我使用了 TTrayIcon,它工作时没有任何问题。对于控制台应用程序,我使用

ShowWindow
函数与
SW_HIDE
TNotifyIconData
在托盘中创建图标,但我遇到了控制台图标仍然出现在 Windows 任务栏中的问题。

procedure HideShowConsoleWindow(isShowForm: Boolean);
var
  Style: LongInt;
  app: THandle;
begin
  app := GetConsoleWindow;
  Style := GetWindowLong(GetConsoleWindow, GWL_EXSTYLE);
  if isShowForm then
  begin
    SetWindowLong(app, GWL_EXSTYLE, Style or WS_EX_TOOLWINDOW and not WS_EX_APPWINDOW);
    ShowWindow(app, SW_HIDE);
  end
  else
  begin
    SetWindowLong(app, GWL_EXSTYLE, Style and not WS_EX_TOOLWINDOW or WS_EX_APPWINDOW);
    ShowWindow(app, SW_SHOW);
  end;
end;

procedure AddTrayIcon;
var
  NotifyIconData: TNotifyIconData;
begin
  FillChar(NotifyIconData, SizeOf(TNotifyIconData), 0);
  NotifyIconData.cbSize := SizeOf(TNotifyIconData);
  NotifyIconData.Wnd := GetConsoleWindow;
  NotifyIconData.uID := 1;
  NotifyIconData.uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
  NotifyIconData.uCallbackMessage := $0400 + 1;
  NotifyIconData.hIcon := LoadIcon(0, IDI_APPLICATION);
  StrPCopy(NotifyIconData.szTip, 'My Console App');
  Shell_NotifyIcon(NIM_ADD, @NotifyIconData);
end;

有没有办法从任务栏隐藏控制台应用程序并将其添加到系统托盘?

delphi console-application delphi-2010
1个回答
0
投票

无法在 Windows 7x64 上使用 Delphi 7 进行重现:我的程序成功隐藏了控制台窗口及其任务按钮:

program HideConsoleWindow;

{$APPTYPE CONSOLE}

const
  SW_HIDE= 0;
  user32= 'user32.dll';
  kernel32= 'kernel32.dll';

type
  HWND= type LongWord;
  BOOL= LongBool;

  function GetConsoleWindow(): HWND; stdcall; external kernel32 name 'GetConsoleWindow';
  function GetForegroundWindow(): HWND; stdcall; external user32 name 'GetForegroundWindow';
  function SetForegroundWindow( h: HWND ): BOOL; stdcall; external user32 name 'SetForegroundWindow';
  function ShowWindow( h: HWND; nCmdShow: Integer ): BOOL; stdcall; external user32 name 'ShowWindow';

var
  hConsole, hFore: HWND;

begin
  hConsole:= GetConsoleWindow();
  if hConsole<> 0 then begin
    if SetForegroundWindow( hConsole ) then begin
      hFore:= GetForegroundWindow();
      if hFore<> 0 then begin
        ShowWindow( hFore, SW_HIDE );
        // Task button should be gone also in recent Windows versions.
      end else begin
        // No foreground window available - still try to set window.
        ShowWindow( hConsole, SW_HIDE );
      end;
    end else begin
      // Console wasn't brought to foreground - still try to set window.
      ShowWindow( hConsole, SW_HIDE );
    end;
  end else begin
    // Couldn't get console window.
  end;
end.

你根本不应该摆弄

GWL_EXSTYLE
。你应该意识到,如果你在现有的控制台中启动这个程序,你也会隐藏该控制台窗口 - 也许这是你不想做的事情,因为它仍然存在,然后你只剩下杀戮它的过程。

© www.soinside.com 2019 - 2024. All rights reserved.