有没有办法减少的时候,我可以在系统托盘中放一个控制台应用程序?

有帮助吗?

解决方案

一个控制台没有窗口本身,以尽量减少。它运行在一个命令提示符窗口。您可能会钩住窗口信息和隐藏最小化窗口。在您的应用程序有可能增加一个托盘图标,就像你会做它在Windows应用程序一样。好了,不知何故该气味 ...

不过:我不知道你为什么要这么做。控制台应用程序是由设计到Windows应用程序不同。因此,也许是改变该应用是一个视窗形式的应用程序的一个选项?

其他提示

是的,你可以做到这一点。 创建一个Windows窗体应用程序并添加 NotifyIcon组件

然后,使用下面的方法(上MSDN )分配并显示控制台

[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();

[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();

[DllImport("kernel32.dll")]
public static extern Boolean AttachConsole(Int32 ProcessId);

当您的控制台是屏幕,捕获的最小化按钮点击,并用它来隐藏控制台窗口和更新的通知图标。您可以使用以下方法找到你的窗口( MSDN上找到):

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.
// Also consider whether you're being lazy or not.
[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

请务必打电话FreeConsole当你准备好关闭应用程序。

using System.Windows.Forms;
using System.Drawing;

static NotifyIcon notifyIcon = new NotifyIcon();
static bool Visible = true;
static void Main(string[] args)
{
    notifyIcon.DoubleClick += (s, e) =>
    {
        Visible = !Visible;
        SetConsoleWindowVisibility(Visible);
    };
    notifyIcon.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
    notifyIcon.Visible = true;
    notifyIcon.Text = Application.ProductName;

    var contextMenu = new ContextMenuStrip();
    contextMenu.Items.Add("Exit", null, (s, e) => { Application.Exit(); });
    notifyIcon.ContextMenuStrip = contextMenu;

    Console.WriteLine("Running!");

    // Standard message loop to catch click-events on notify icon
    // Code after this method will be running only after Application.Exit()
    Application.Run(); 

    notifyIcon.Visible = false;
}

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void SetConsoleWindowVisibility(bool visible)
{
    IntPtr hWnd = FindWindow(null, Console.Title);
    if (hWnd != IntPtr.Zero)
    {
        if (visible) ShowWindow(hWnd, 1); //1 = SW_SHOWNORMAL           
        else ShowWindow(hWnd, 0); //0 = SW_HIDE               
    }
}

我使用 TrayRunner 正是这种目的。从本质上讲,它包装一个控制台应用程序捕获所有输出。但最小化时,它最小化到系统托盘,而不是任务栏。你甚至可以自定义显示什么图标最小化时。我用它的东西,如Tomcat或Apache腾出我的任务栏上的空间,而不运行它们作为Windows服务。

[DllImport("user32.dll")]
internal static extern bool SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, Int32 lParam);
static Int32 WM_SYSCOMMAND = 0x0112;
static Int32 SC_MINIMIZE = 0x0F020;

static void Main(string[] args)
{
    SendMessage(Process.GetCurrentProcess().MainWindowHandle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
}

您不能隐藏一个控制台应用程序,因为它实际上并没有一个窗口去隐藏,看到它是如何在控制台上运行(控制台本身只是一个控制台窗口,而不是在其上运行的应用程序)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top