
1 Simple Requirements
- Use open-source control library
- Declare tray menu in XAML, just like adding a ContextMenu to a control
- Encapsulates commonly used commands, such as: open main window, exit application, etc.

I added a tray menu in TerminalMACS, and the final effect is:


2 How to do it?
【Step 1】In an existing WPF project, add the HandyControl library and install it:

You ask why use the HC control library? First, take a look at the demo effects:



Common tray effects should be sufficient, right? And to achieve these effects, the code we need to write is really minimal because HC has already encapsulated them, we can just use them directly.
【Step 2】Add the HandyControl namespace in the window
xmlns:hc="https://handyorg.github.io/handycontrol"
【Step 3】Declare the key 19 lines of code for the tray menu
<hc:NotifyIcon x:Name="NotifyIconContextContent"
Text="{markup:I18n {x:Static i18NResources:Language.AppTitle}}"
Visibility="Visible"
Icon="/Images/logo.ico">
<hc:NotifyIcon.ContextMenu>
<ContextMenu>
<MenuItem Command="hc:ControlCommands.PushMainWindow2Top" Header="{markup:I18n {x:Static i18NResources:Language.PushMainWindow2Top}}"/>
<MenuItem Command="hc:ControlCommands.ShutdownApp" Header="{markup:I18n {x:Static i18NResources:Language.Exit}}"/>
</ContextMenu>
</hc:NotifyIcon.ContextMenu>
<hc:Interaction.Triggers>
<hc:EventTrigger EventName="Click">
<hc:EventToCommand Command="hc:ControlCommands.PushMainWindow2Top"/>
</hc:EventTrigger>
</hc:Interaction.Triggers>
</hc:NotifyIcon>
The code above essentially completes a tray menu. Let me briefly explain:
- NotifyIcon is the tray menu control, Text displays the tray menu name, hovering over the tray icon shows this string as ToolTip, usually the application name, as shown below:

- hc:NotifyIcon.ContextMenu is used to declare menu items. Currently, this project has added two menus: open main window and exit application. The corresponding commands for these two menus have been encapsulated by HC, making them easy to use.
- Additionally, clicking the tray menu can also bring up the main application window.
【Step 4】Hide the main window instead of exiting when manually closing it
After adding the tray menu, when closing the main window, the OnClosing event should be overridden to hide the main window instead of directly closing it.
protected override void OnClosing(CancelEventArgs e)
{
this.Hide();
e.Cancel = true;
}
3 More References
For more demo source code, please refer to HandyControl
The source code for this article is at TerminalMACS