需要了解:
那麼我們的思路是:
別慌,還需要你解決的問題:
/*
* 控制檯禁用關閉按鈕並最小化到系統托盤演示
*
* 通過ConsoleWin32類來進行控制
* 添加引用 System.Runtime.InteropServices; 和 System.Threading; 用於禁用關閉按鈕
* 添加引用 System.Drawing; 和 System.Windows.Forms; 用於系統托盤
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
namespace Tray_beta_1
{
class Program
{
static bool _IsExit = false;
static void Main(string[] args)
{
Console.Title = "TestConsoleLikeWin32";
ConsoleWin32Helper.ShowNotifyIcon();
ConsoleWin32Helper.DisableCloseButton(Console.Title);
Thread threadMonitorInput = new Thread(new ThreadStart(MonitorInput));
threadMonitorInput.Start();
while (true)
{
Application.DoEvents();
if (_IsExit)
{
break;
}
}
}
static void MonitorInput()
{
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
{
_IsExit = true;
Thread.CurrentThread.Abort();
}
}
}
}
class ConsoleWin32Helper
{
static ConsoleWin32Helper()
{
_NotifyIcon.Icon = new Icon(@"G:\BruceLi Test\ConsoleAppTest\ConsoleApps\Tray\small.ico");
_NotifyIcon.Visible = false;
_NotifyIcon.Text = "tray";
ContextMenu menu = new ContextMenu();
MenuItem item = new MenuItem();
item.Text = "右鍵菜單,還沒有添加事件";
item.Index = 0;
menu.MenuItems.Add(item);
_NotifyIcon.ContextMenu = menu;
_NotifyIcon.MouseDoubleClick += new MouseEventHandler(_NotifyIcon_MouseDoubleClick);
}
static void _NotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
Console.WriteLine("托盤被雙擊.");
}
#region 禁用關閉按鈕
[DllImport("User32.dll", EntryPoint = "FindWindow")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
static extern IntPtr GetSystemMenu(IntPtr hWnd, IntPtr bRevert);
[DllImport("user32.dll", EntryPoint = "RemoveMenu")]
static extern IntPtr RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);
/// <summary>
/// 禁用關閉按鈕
/// </summary>
/// <param name="consoleName">控制檯名字</param>
public static void DisableCloseButton(string title)
{
//線程睡眠,確保closebtn中能夠正常FindWindow,否則有時會Find失敗。。
Thread.Sleep(100);
IntPtr windowHandle = FindWindow(null, title);
IntPtr closeMenu = GetSystemMenu(windowHandle, IntPtr.Zero);
uint SC_CLOSE = 0xF060;
RemoveMenu(closeMenu, SC_CLOSE, 0x0);
}
public static bool IsExistsConsole(string title)
{
IntPtr windowHandle = FindWindow(null, title);
if (windowHandle.Equals(IntPtr.Zero)) return false;
return true;
}
#endregion
#region 托盤圖標
static NotifyIcon _NotifyIcon = new NotifyIcon();
public static void ShowNotifyIcon()
{
_NotifyIcon.Visible = true;
_NotifyIcon.ShowBalloonTip(3000, "", "我是托盤圖標,用右鍵點擊我試試,還可以雙擊看看。", ToolTipIcon.None);
}
public static void HideNotifyIcon()
{
_NotifyIcon.Visible = false;
}
#endregion
}
}
附加題: