c# - 每秒刷新和更新上下文菜单条
问题描述
我正在开发一个仅作为托盘应用程序存在的应用程序,该应用程序为您提供上下文菜单,允许您与特定的 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() 方法的部分;已经用过。
解决方案
我想出的解决方案是将循环保持在 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();
}
推荐阅读
- python - pip安装后无法导入sendgrid
- javascript - 单击按钮,它将该信息发送到页面上的另一个框中
- java - 求出满足 min(S) + max(S) <= K 的非空子集 S 的数量
- python - 这种方式有更短的方法吗?
- c++ - C ++中的Mtcnn人脸对齐
- c# - LINQ 为异步方法选择模拟
- python - 尽管使用 POST,但不允许使用 Flask- 方法
- c# - 将文本和应用程序特定数据复制到剪贴板
- c++ - unzip.obj 可能缺少哪些库:错误 LNK2019?
- javascript - Css 导致 Angularjs 动态 div 结果到 Jam