首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何制作仅在系统托盘中运行的.NET Windows窗体应用程序?

如何制作仅在系统托盘中运行的.NET Windows窗体应用程序?
EN

Stack Overflow用户
提问于 2009-06-15 09:26:51
回答 12查看 233.7K关注 0票数 254

要使Windows窗体应用程序能够在系统托盘中运行,我需要做什么?

不是可以最小化到托盘的应用程序,而是只存在于托盘中的应用程序,仅限于

  • 图标
  • 一个工具提示,和
  • 一个“右击”菜单。
EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2012-04-20 16:33:51

代码项目文章创建任务托盘应用程序给出了一个非常简单的解释和示例,说明如何创建只存在于System中的应用程序。

基本上,将Program.cs中的Program.cs行更改为启动继承自ApplicationContext的类,并让该类的构造函数初始化NotifyIcon

代码语言:javascript
运行
复制
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new MyCustomApplicationContext());
    }
}


public class MyCustomApplicationContext : ApplicationContext
{
    private NotifyIcon trayIcon;

    public MyCustomApplicationContext ()
    {
        // Initialize Tray Icon
        trayIcon = new NotifyIcon()
        {
            Icon = Resources.AppIcon,
            ContextMenu = new ContextMenu(new MenuItem[] {
                new MenuItem("Exit", Exit)
            }),
            Visible = true
        };
    }

    void Exit(object sender, EventArgs e)
    {
        // Hide tray icon, otherwise it will remain shown until user mouses over it
        trayIcon.Visible = false;

        Application.Exit();
    }
}
票数 132
EN

Stack Overflow用户

发布于 2009-06-15 09:46:10

正如mat1t所说--您需要向应用程序中添加一个NotifyIcon,然后使用如下代码设置工具提示和上下文菜单:

代码语言:javascript
运行
复制
this.notifyIcon.Text = "This is the tooltip";
this.notifyIcon.ContextMenu = new ContextMenu();
this.notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Option 1", new EventHandler(handler_method)));

此代码仅显示系统托盘中的图标:

代码语言:javascript
运行
复制
this.notifyIcon.Visible = true;  // Shows the notify icon in the system tray

如果您有一份表格(无论出于何种原因),将需要下列内容:

代码语言:javascript
运行
复制
this.ShowInTaskbar = false;  // Removes the application from the taskbar
Hide();

右击获取上下文菜单将被自动处理,但是如果您想在左键上执行一些操作,则需要添加一个click处理程序:

代码语言:javascript
运行
复制
    private void notifyIcon_Click(object sender, EventArgs e)
    {
        var eventArgs = e as MouseEventArgs;
        switch (eventArgs.Button)
        {
            // Left click to reactivate
            case MouseButtons.Left:
                // Do your stuff
                break;
        }
    }
票数 19
EN

Stack Overflow用户

发布于 2009-06-15 10:51:38

我用.NET 1.1编写了一个traybar应用程序,我不需要表单。

首先,将项目的启动对象设置为在模块中定义的Sub Main

然后以编程方式创建组件:NotifyIconContextMenu

一定要包括一个MenuItem“退出”或类似的。

ContextMenu绑定到NotifyIcon

调用Application.Run()

在退出MenuItem的事件处理程序中,一定要调用set NotifyIcon.Visible = False,然后调用Application.Exit()。将所需内容添加到ContextMenu中并正确处理:)

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/995195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档