NotifyIcon.BalloonTipText
is plain string and so it is not possible. In addition, since NotifyIcon
is WinForms component, you cannot use WPF components directly from it.
You will have some options.
Option 1: Use Hardcodet NotifyIcon for WPF.
Option 2: Implement a mechanism to open a WPF window when NotifyIcon
is clicked. For example, create a class to hold and show NofityIcon
as follows.
// using System;
// using System.Runtime.InteropServices;
// using System.Windows;
// using System.Windows.Forms;
public class NotifyIconHolder
{
public event EventHandler<Point>? MouseRightClick;
public event EventHandler<Point>? MouseLeftClick;
public event EventHandler<Point>? MouseDoubleClick;
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
public static implicit operator System.Windows.Point(POINT p) => new(p.x, p.y);
}
private NotifyIcon? _notifyIcon;
public void ShowIcon(System.Drawing.Icon icon, string text)
{
if (_notifyIcon is null)
{
_notifyIcon = new NotifyIcon()
{
Icon = icon,
Text = text
};
_notifyIcon.MouseClick += (_, e) =>
{
if (GetCursorPos(out POINT position))
{
switch (e.Button)
{
case MouseButtons.Left:
MouseLeftClick?.Invoke(null, position);
break;
case MouseButtons.Right:
MouseRightClick?.Invoke(null, position);
break;
}
}
};
_notifyIcon.MouseDoubleClick += (_, _) =>
{
if (GetCursorPos(out POINT position))
{
MouseDoubleClick?.Invoke(null, position);
}
};
_notifyIcon.Visible = true;
}
}
public void HideIcon()
{
_notifyIcon?.Dispose();
_notifyIcon = null;
}
}
Its usage. You will need to think about where to show a WPF window but it's another issue.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private NotifyIconHolder? _holder;
private void OnLoaded(object sender, RoutedEventArgs e)
{
_holder = new NotifyIconHolder();
_holder.MouseLeftClick += OnNotifyIconLeftClick;
_holder.MouseRightClick += OnNotifyIconRightClick;
// Assuming application's resources include an Icon (.ico).
_holder.ShowIcon(Properties.Resources.Icon, "Sample");
}
private void OnNotifyIconLeftClick(object? sender, Point e)
{
// Show the WPF window for left click.
}
private void OnNotifyIconRightClick(object? sender, Point e)
{
// Show the WPF window for right click.
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
_holder?.HideIcon();
}
}