首页 > 解决方案 > 每秒刷新和更新上下文菜单条

问题描述

我正在开发一个仅作为托盘应用程序存在的应用程序,该应用程序为您提供上下文菜单,允许您与特定的 Windows 服务进行交互。我目前遇到的问题是我需要不断检查服务是否仍在运行,并更新 Main() 方法中包含的信息。我遇到的问题超出了初始状态检查,我只能通过基于交互的方法显示/隐藏 ToolStripItems。我需要在交互和基于时间的自动检查中都发生这种情况。

我的第一次尝试是一个无限循环,直到用户点击退出。在伪代码中,它如下所示。

status = getStatus;
//show/hide based on status
 if (status == "Running")
 {
 _stopButton.Visible = true;
}
 if (count == 0)
{
//when run the first time it starts the application
  Application.Run();
  count = 1;
}
//every second it should check everything however we never end up seeing this part
 Thread.Sleep(1000);
 Console.WriteLine("checked");
}

我花了一段时间查看上下文菜单条,看看是否有可以添加的自动更新项目,但似乎并非如此。总而言之,我目前不确定如何正确地每秒进行状态更新,并且一旦 Application.Run(); 也可以访问 Main() 方法的部分;已经用过。

标签: c#winforms

解决方案


我想出的解决方案是将循环保持在 Main 方法中,然后使用 System.Windows.Forms.Timer。我还需要将 Application.Run() 换成 Application.DoEvents()。工作代码如下所示

            myTimer.Interval = 1000;
            myTimer.Start();
            while (!end)
            {



                status = getStatus();
                if (status == "Running")
                {
                    trayicon.Icon = Properties.Resources.icon_1x;
                    _stopButton.Visible = true;
                    _pauseButton.Visible = true;
                    _startButton.Visible = false;
                }
               Application.DoEvents();
             }

推荐阅读