C# WinForm 工具列小圖示 詳細介紹(動態新增、滑鼠事件、顯示通知、右鍵選單)

動態新增工具列小圖示

            
NotifyIcon notifyIcon = new()
{
    Icon = SystemIcons.Application,
    Visible = true,
    Text = "Ruyut",
};
this.components?.Add(notifyIcon);
    

上面除了 Text 以外其他都是必要設定,如果沒有 Icon 則無法顯示,預設為不可見也需要先調整 Visible 屬性,然後在透過第 7 行將之新增。

NotifyIcon 的滑鼠事件

如果想要讓 WinForm 在最小化時透過滑鼠左鍵點擊顯示 WinForm ,可以使用 MouseClick 事件
    
notifyIcon.MouseClick += (sender, args) =>
{
    if (args.Button == MouseButtons.Left)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
    }
};
    

註:此為簡易示範,不會記錄視窗是否最大化

顯示通知

可以使用下面這行顯示通知:
    
notifyIcon.ShowBalloonTip(1000, "Ruyut", "Hello", ToolTipIcon.Info);
    

有四個參數,分別是顯示毫秒、標題、內容、圖示,圖示可以使用的列舉有: None, Info, Warning, Error

而上方的內容為專案名稱,如果想要更改也可以在專案的 csproj 檔案內用 AssemblyName 標籤更改,例如:
    

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net6.0-windows</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWindowsForms>true</UseWindowsForms>
        <ImplicitUsings>enable</ImplicitUsings>
        <AssemblyName>RuyutWinForms</AssemblyName>
    </PropertyGroup>

</Project>
    

滑鼠右鍵選單

要增加滑鼠右鍵選單很簡單,只要拖拉增加 ContextMenuStrip 物件,並系結到 NotifyIcon 的 ContextMenuStrip 屬性即可,這裡就來示範使用程式動態新增,增加一個「退出應用程式」的按鈕:
    
ContextMenuStrip contextMenuStrip = new();
contextMenuStrip.Items.Add("退出應用程式", null, (sender, args) => Application.Exit());
notifyIcon.ContextMenuStrip = contextMenuStrip;
    


留言