作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从 C# 中的默认 Windows 窗体应用程序开始,我所做的更改只是 Progam.cs。从主要功能,我改变了
Application.Run(new Form1());
到
Application.Run(new MyCustomApplicationContext());
它指的是一个自定义类 (MyCustomApplicationContext:ApplicationContext),它将我的程序作为系统托盘图标而不是 Windows 窗体运行。构造函数包含以下代码:
private NotifyIcon trayIcon = new NotifyIcon();
trayIcon.ContextMenu = new ContextMenu(
new MenuItem[]
{
new MenuItem("Exit", Exit)
});
这允许用户右键单击该图标,为他们提供一个带有“退出”选项的上下文菜单,该选项将运行一个关闭程序的功能。
在 MyCustomApplicationContext 的构造函数的末尾,我在名为 Update() 的类中调用了一个递归函数,它执行一个 ping 函数并根据 ping 延迟更改系统托盘图标。
不幸的是,我相信因为它是递归的,所以不允许运行任何其他代码,所以右键单击上下文菜单永远不会出现。我宁愿通过事件调用 Update() 函数,例如 System.Timers.Timer Elapsed 事件。我只是不知道事件如何工作或将代码放在哪里。
最佳答案
正如 dmay 所说,您可以使用 Timer 类来调用您的更新功能;但是,通过阅读您的描述,听起来您也需要在这里考虑线程。
...
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += UpdateTimer;
aTimer.Interval = 2000;
aTimer.Enabled = true;
...
public delegate void delUpdate(); // This is your delegate. Put it in your MyCustomApplicationContext class.
// This method will invoke your delegate method.
public void UpdateTimer(object sender, ElapsedEventArgs e)
{
this.Invoke((delUpdate)Update);
}
使用 Invoke 方法的原因是计时器将从另一个线程运行,如果您想调用更新用户界面的方法,您需要 Invoke你的控制。否则,您将通过尝试访问不属于触发计时器的线程的对象来生成异常。
关于c# - 如何在 C# 系统托盘应用程序中重复运行代码(如定时器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17936944/
我是一名优秀的程序员,十分优秀!