Mel*_*sus 14 c# console system-tray .net-3.5
有没有办法在最小化时将控制台应用程序放在系统托盘中?
我使用.Net 3.5和c#
CLa*_*RGe 22
是的,你可以这样做.创建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);
Run Code Online (Sandbox Code Playgroud)
当您的控制台在屏幕上时,捕获最小化按钮单击并使用它来隐藏控制台窗口并更新通知图标.您可以使用以下方法找到您的窗口(在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);
Run Code Online (Sandbox Code Playgroud)
每当您准备关闭应用程序时,请务必致电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
}
}
Run Code Online (Sandbox Code Playgroud)
控制台没有窗口可以自行最小化.它在命令提示符窗口中运行.您可以挂钩窗口消息并在最小化时隐藏窗口.在您的应用程序中,可以添加托盘图标,就像在Windows应用程序中一样.好吧,不知怎的,这闻起来 ......
但是:我不确定你为什么要这样做.控制台应用程序的设计与Windows应用程序不同.因此,也许可以选择将应用程序更改为Windows窗体应用程序?
| 归档时间: |
|
| 查看次数: |
26855 次 |
| 最近记录: |