C#使用WPF实现托盘图标

13

虽然我已经在 Unity3D 中编写 C# 脚本几年了,但对编程 C# 还是很新手。 我目前正在尝试制作一个 WPF 托盘图标,我在网上找到的所有资源都告诉我要使用

System.Windows.Forms

但是在我的System.Windows中并没有.Forms可用,我不知道为什么。有谁能帮我吗?

2个回答

35

你需要添加对System.Window.Forms和System.Drawing程序集的引用,然后像这样使用它。假设你尝试将窗口最小化到托盘图标中,并在用户单击该图标时再次显示它:

public partial class Window : System.Windows.Window
{

    public Window()
    {
        InitializeComponent();

        System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
        ni.Icon = new System.Drawing.Icon("Main.ico");
        ni.Visible = true;
        ni.DoubleClick += 
            delegate(object sender, EventArgs args)
            {
                this.Show();
                this.WindowState = WindowState.Normal;
            };
    }

    protected override void OnStateChanged(EventArgs e)
    {
        if (WindowState == WindowState.Minimized)
            this.Hide();

        base.OnStateChanged(e);
    }
}

1
优秀的词汇参考帮助我找到了如何和在哪里实现。 现在我有了托盘图标,谢谢 =) - Logan
2
如果您在带有 System.Windows 引用的窗口中运行,可能会遇到一些歧义问题。我通过向 using 添加名称来解决它:using WinForms = System.Windows.Forms; 然后通过 WinForms.NotifyIcon notifyIcon = new WinForms.NotifyIcon(); 调用它。 - Andrew Grinder
工作得非常出色,赞! - IssamTP

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接