简体   繁体   English

Systray应用程序退出

[英]Systray Application Exiting

I have a small, simple C# application which updates an icon in the system tray. 我有一个小的,简单的C#应用​​程序,用于更新系统托盘中的图标。 I use it to graphically show the CPU usage. 我用它以图形方式显示CPU使用率。 The application works great. 该应用程序运行良好。 I keep the Window hidden and don't show it in the taskbar so it doesn't get in the way. 我将“窗口”保持隐藏状态,并且不将其显示在任务栏中,因此不会妨碍您。

My issue is that it will run great for a while. 我的问题是它将运行一段时间。 Often several hours. 经常几个小时。 But then it will mysteriously quit. 但随后它将神秘地退出。 No warnings. 没有警告。 Nothing. 没有。 The icon is just gone and the program is no longer running. 图标刚刚消失,程序不再运行。 I have tested the program in the debugger under varying conditions, so I don't think that is it. 我已经在各种条件下在调试器中测试了该程序,所以我认为不是。 Is there something obvious I am missing? 有什么明显的我想念的东西吗? If the program encounters an error and quits should I be expecting a message if the Form is hidden? 如果程序遇到错误并退出,是否应该在隐藏表单的情况下收到消息? Is there some "keep-alive" message or something that I need to handle? 是否有一些“保持活动”消息或我需要处理的信息?

Here is the relevant section of code: 这是代码的相关部分:

public Form1()
{
    InitializeComponent();

    trayIcon = new NotifyIcon();
    trayIcon.Text = "CPU Utilization";
    trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);

    trayIcon.Visible = true;

    update = new Thread(new ThreadStart(UpdateCPU));
    update.Start();
}

protected override void OnLoad(EventArgs e)
{
    Visible = false;
    ShowInTaskbar = false;

    base.OnLoad(e);
}

private void UpdateCPU()
{
    Bitmap bm = new Bitmap(32, 32);
    Graphics g = Graphics.FromImage(bm);

    while (true)
    {
        g.FillRectangle(new SolidBrush(c3), 17, 17, 15, 15);
        trayIcon.Icon = System.Drawing.Icon.FromHandle(bm.GetHicon());

        Thread.Sleep(1000);
    }
}

Any help would be greatly appreciated! 任何帮助将不胜感激!

I would suggest you add an Unhandled Exception Handler 我建议您添加一个未处理的异常处理程序

Global Exception Handling for winforms control Winforms控制的全局异常处理

An Exception is likely being thrown, causing your program to exit. 可能会引发异常,从而导致程序退出。

Then, introduce logging to log what the Exception was. 然后,引入日志记录以记录异常是什么。 Personally I prefer NLog . 我个人更喜欢NLog

I'm a bit surprised that you can update trayIcon from a non-UI thread without receiving a cross-thread exception. 我很惊讶您可以从非UI线程更新trayIcon而不会收到跨线程异常。

The documentation seems to agree with Viktor Latypov's comment, you should be doing something like this: 文档似乎同意Viktor Latypov的评论,您应该执行以下操作:

Icon newIcon = Icon.FromHandle(bm.GetHicon());

trayIcon.Icon = newIcon;

DestroyIcon(newIcon.Handle);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM