C# 实现WPF App最小化托盘测试

76 篇文章 1 订阅
这篇博客介绍了如何在WPF应用中创建一个通知区域图标,并实现右键菜单功能。通过使用System.Windows.Forms.NotifyIcon类,结合WPF的依赖属性和事件处理,实现了图标显示、菜单项点击以及鼠标事件的响应。当窗口最小化时,图标显示在任务栏通知区域,双击图标可以恢复窗口。同时,提供了各种菜单项的点击事件处理,如显示消息框。
摘要由CSDN通过智能技术生成

xmlns:winForm =“clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms”

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ComponentModel;

using Drawing = System.Drawing;

using Forms = System.Windows.Forms; //Forms.NotifyIcon

using System.Windows;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Markup;

namespace WpfApp

{

public class NotificationAreaIcon : FrameworkElement

{

    Forms.NotifyIcon notifyIcon;

    public static readonly RoutedEvent MouseClickEvent = EventManager.RegisterRoutedEvent(

        "MouseClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon));

    public static readonly RoutedEvent MouseDoubleClickEvent = EventManager.RegisterRoutedEvent(

        "MouseDoubleClick", RoutingStrategy.Bubble, typeof(MouseButtonEventHandler), typeof(NotificationAreaIcon));

    public static readonly DependencyProperty IconProperty =

        DependencyProperty.Register("Icon", typeof(ImageSource), typeof(NotificationAreaIcon));

    public static readonly DependencyProperty TextProperty =

        DependencyProperty.Register("Text", typeof(string), typeof(NotificationAreaIcon));

    public static readonly DependencyProperty FormsContextMenuProperty =

        DependencyProperty.Register("MenuItems", typeof(List<Forms.MenuItem>), typeof(NotificationAreaIcon), new PropertyMetadata(new List<Forms.MenuItem>()));

    protected override void OnInitialized(EventArgs e)

    {

        base.OnInitialized(e);

        // Create and initialize the window forms notify icon based

        notifyIcon = new Forms.NotifyIcon();

        notifyIcon.Text = Text;

        if (!DesignerProperties.GetIsInDesignMode(this))

        {

            notifyIcon.Icon = FromImageSource(Icon);

        }

        notifyIcon.Visible = FromVisibility(Visibility);

        if (this.MenuItems != null && this.MenuItems.Count > 0)

        {

            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(this.MenuItems.ToArray());

        }

        notifyIcon.MouseDown += OnMouseDown;

        notifyIcon.MouseUp += OnMouseUp;

        notifyIcon.MouseClick += OnMouseClick;

        notifyIcon.MouseDoubleClick += OnMouseDoubleClick;

        Dispatcher.ShutdownStarted += OnDispatcherShutdownStarted;

    }

    private void OnDispatcherShutdownStarted(object sender, EventArgs e)

    {

        notifyIcon.Dispose();

    }

    private void OnMouseDown(object sender, Forms.MouseEventArgs e)

    {

        OnRaiseEvent(MouseDownEvent, new MouseButtonEventArgs(

            InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button)));

    }

    private void OnMouseUp(object sender, Forms.MouseEventArgs e)

    {

        OnRaiseEvent(MouseUpEvent, new MouseButtonEventArgs(

            InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button)));

    }

    private void OnMouseDoubleClick(object sender, Forms.MouseEventArgs e)

    {

        OnRaiseEvent(MouseDoubleClickEvent, new MouseButtonEventArgs(

            InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button)));

    }

    private void OnMouseClick(object sender, Forms.MouseEventArgs e)

    {

        OnRaiseEvent(MouseClickEvent, new MouseButtonEventArgs(

            InputManager.Current.PrimaryMouseDevice, 0, ToMouseButton(e.Button)));

    }

    private void OnRaiseEvent(RoutedEvent handler, MouseButtonEventArgs e)

    {

        e.RoutedEvent = handler;

        RaiseEvent(e);

    }

    public List<Forms.MenuItem> MenuItems

    {

        get { return (List<Forms.MenuItem>)GetValue(FormsContextMenuProperty); }

        set { SetValue(FormsContextMenuProperty, value); }

    }

    public ImageSource Icon

    {

        get { return (ImageSource)GetValue(IconProperty); }

        set { SetValue(IconProperty, value); }

    }

    public string Text

    {

        get { return (string)GetValue(TextProperty); }

        set { SetValue(TextProperty, value); }

    }

    public event MouseButtonEventHandler MouseClick

    {

        add { AddHandler(MouseClickEvent, value); }

        remove { RemoveHandler(MouseClickEvent, value); }

    }

    public event MouseButtonEventHandler MouseDoubleClick

    {

        add { AddHandler(MouseDoubleClickEvent, value); }

        remove { RemoveHandler(MouseDoubleClickEvent, value); }

    }

    #region Conversion members

    private static Drawing.Icon FromImageSource(ImageSource icon)

    {

        if (icon == null)

        {

            return null;

        }

        Uri iconUri = new Uri(icon.ToString());

        return new Drawing.Icon(Application.GetResourceStream(iconUri).Stream);

    }

    private static bool FromVisibility(Visibility visibility)

    {

        return visibility == Visibility.Visible;

    }

    private MouseButton ToMouseButton(Forms.MouseButtons button)

    {

        switch (button)

        {

            case Forms.MouseButtons.Left:

                return MouseButton.Left;

            case Forms.MouseButtons.Right:

                return MouseButton.Right;

            case Forms.MouseButtons.Middle:

                return MouseButton.Middle;

            case Forms.MouseButtons.XButton1:

                return MouseButton.XButton1;

            case Forms.MouseButtons.XButton2:

                return MouseButton.XButton2;

        }

        throw new InvalidOperationException();

    }

    #endregion Conversion members

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

namespace WpfApp

{

/// <summary>

/// MainWindow.xaml 的交互逻辑

/// </summary>

public partial class MainWindow : Window

{

    public MainWindow()

    {

        InitializeComponent();

        this.ShowInTaskbar = false;

    }

    private void Window\_StateChanged(object sender, EventArgs e)

    {

        if (this.WindowState == WindowState.Minimized)

        {

            this.Hide();

        }

        if (this.WindowState == WindowState.Normal || this.WindowState == WindowState.Maximized)

        {

            this.Show();

            this.Activate();

        }

    }

    private void Window\_SizeChanged(object sender, SizeChangedEventArgs e)

    {

        if (this.WindowState == WindowState.Minimized)

        {

            this.ShowInTaskbar = false;

            this.Hide();

            this.notfyicon.Visibility = Visibility.Visible;

        }

    }

    //双击托盘图标恢复需要响应notifyIcon的DoubleClick消息

    private void NotificationAreaIcon\_MouseDoubleClick(object sender, MouseButtonEventArgs e)

    {

        if (this.WindowState == WindowState.Minimized)

        {

            this.Show();

            WindowState = WindowState.Normal;

            this.notfyicon.Visibility = Visibility.Hidden;

            this.ShowInTaskbar = true;

        }

    }

    private void MenuItemLeave\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示离线!");

    }

    private void MenuItemNoBother\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示请勿打扰!");

    }

    private void MenuItemBusy\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示在忙!");

    }

    private void MenuItemHidden\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示隐身!");

    }

    private void MenuItemOffline\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示暂时离开!");

    }

    private void MenuItemAboutUs\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示关于我们!");

    }

    private void MenuItemExit\_Click(object sender, EventArgs e)

    {

        this.Close();

    }

    private void MenuIteOnline\_Click(object sender, EventArgs e)

    {

        MessageBox.Show("提示上线!");

    }

}

}

运行:
在这里插入图片描述

最小化,在状态栏显示指定logo.

右键弹出菜单:
在这里插入图片描述
代码可实现响应任何一个菜单的事件。

WPF最小化托盘(System Tray)的实现可以通过以下步骤来完成: 1. 首先,在XAML文件中创建一个托盘图标。可以使用Rectangle、Ellipse或Image等控件来作为图标,然后设置图标的宽度、高度和颜色等属性。 ```xml <Rectangle Width="16" Height="16" Fill="Red" /> ``` 2. 在MainWindow.xaml.cs文件中,首先添加以下命名空间: ```csharp using System.Windows.Forms; ``` 3. 在MainWindow.xaml.cs文件中,创建一个NotifyIcon对象,并在窗口加载事件中进行初始化,包括设置托盘图标和右键菜单等属性。 ```csharp private NotifyIcon notifyIcon; private void MainWindow_Loaded(object sender, RoutedEventArgs e) { notifyIcon = new NotifyIcon(); notifyIcon.Icon = new System.Drawing.Icon("Icon.ico"); notifyIcon.Visible = true; notifyIcon.Text = "My WPF Application"; ContextMenu menu = new ContextMenu(); // 创建右键菜单 MenuItem showMenuItem = new MenuItem(); showMenuItem.Text = "显示"; showMenuItem.Click += new EventHandler(ShowMenuItem_Click); menu.MenuItems.Add(showMenuItem); MenuItem exitMenuItem = new MenuItem(); exitMenuItem.Text = "退出"; exitMenuItem.Click += new EventHandler(ExitMenuItem_Click); menu.MenuItems.Add(exitMenuItem); notifyIcon.ContextMenu = menu; } ``` 4. 创建点击事件处理方法来处理托盘图标的左键双击事件,以及右键菜单中的"显示"和"退出"事件。 ```csharp private void TrayIcon_DoubleClick(object sender, EventArgs e) { this.Show(); // 双击托盘图标时显示主窗口 this.WindowState = WindowState.Normal; } private void ShowMenuItem_Click(object sender, EventArgs e) { this.Show(); // 右键菜单中点击"显示"时显示主窗口 this.WindowState = WindowState.Normal; } private void ExitMenuItem_Click(object sender, EventArgs e) { this.Close(); // 右键菜单中点击"退出"时关闭应用程序 } ``` 5. 最后,在MainWindow.xaml文件中的Window标签中添加Loaded事件调用MainWindow_Loaded方法。 ```xml <Window x:Class="Demo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WPF最小化托盘Demo" Height="450" Width="800" Loaded="MainWindow_Loaded"> <!-- 主窗口内容 --> </Window> ``` 通过以上步骤,我们可以实现一个简单的WPF最小化托盘Demo,点击托盘图标可以显示主窗口,右键菜单中可以选择显示或退出应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值