
1 Simple requirement
- Use open source control libraries
- Declaring a tray menu in XAML is like adding a ContextMenu to a control
- Encapsulates common commands, such as: open the main form, exit the application, etc.

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


2 How to do it?
[Step 1] Add the HandyControl library to the WPF project you have created and install:

You asked me why I use the HC control library? Let's first look at the Demo effect:



The effects of commonly used trays should be satisfactory, right? To achieve these effects, there is really not much code we need to code ourselves, because HC has been encapsulated and we can use it directly.
[Step 2] Add HandyControl namespace to the form
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>
With the code above, a tray menu is basically done. Let me briefly say:
- NotifyIcon is a tray menu control, Text displays the tray menu name, place the mouse on the tray icon, ToolTip displays the string, and generally displays the application name, as shown in the following figure:

- hc:NotifyIcon.ContextMenu is used to declare menu items. This project currently has two menus: open the main form and exit the application. The corresponding commands HC for these two menus have been encapsulated for easy use. - In addition, click the tray menu to pop up the main application window
[Step 4] When manually closing the main form, hide it without exiting
After adding the tray menu, when closing the main form, you should override the OnClosing event to hide the main form rather than closing it directly.
protected override void OnClosing(CancelEventArgs e)
{
this.Hide();
e.Cancel = true;
}
3 More references
更多 Demo 源码请参考 HandyControl
本文源码TerminalMACS