using System;
using System.Data.SQLite;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
using Tulpep.NotificationWindow;
public partial class Form1 : Form
{
System.Timers.Timer timer = null;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
if (timer == null)
{
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(ObjTimer_Elapsed);
timer.Interval = 10000;
timer.Start();
}
}
private void ObjTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
PopupNotifier pop = new PopupNotifier();
pop.TitleText = "Test";
pop.ContentText = "Hello World";
pop.Popup();
//MessageBox.Show(""); !!! here is problem !!!
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
我在这里使用Tulpep notification来创建桌面通知。我的表单中有一个开始按钮。单击开始按钮时,计时器开始弹出桌面通知。但只有当我不对MessageBox.Show("");
发表评论时才显示通知。如果我删除或评论MessageBox.Show("");
,则不会显示通知。我在两种情况下进行调试,两种情况都没有错误或异常。
有人知道为什么会这样吗?
我正在使用.net framework 4.5.2,visual studio 2015, windows 8
。
答案 0 :(得分:6)
PopupNotifier
。由于计时器的处理程序在不同的线程中运行,因此您需要调用表单来解决问题。
this.Invoke((MethodInvoker)delegate
{
PopupNotifier pop = new PopupNotifier();
pop.TitleText = "Test";
pop.ContentText = "Hello World";
pop.Popup();
});
答案 1 :(得分:2)
创建一个静态类 ControlExtensions :
public static void InvokeOnUiThreadIfRequired(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
此后,再次转到调用 Tulpep.NotificationWindow。的行,并将主表单分配给这样的变量:
//popup var is the notificationwindow inside form1
Form1 ff = (Form1)Application.OpenForms["Form1"];
ff.InvokeOnUiThreadIfRequired(() =>
{
ff.popup.Image = Properties.Resources.info_icon; //icon from resources
ff.popup.TitleText = title; // some text here
ff.popup.ContentText = contentMessage; // some text here
ff.popup.Popup();
});
现在您调用主窗体并显示NotificationWindow
答案 2 :(得分:0)
我遇到了同样的问题,但是使用Task.Run()时,我尝试在SomeMethod内部调用Popup时没有运气。使用Invoke解决。希望这对某人有帮助。
Task.Run(() => {
SomeMethod(); //Some method that executes in background
//Popup when SomeMethod is finished using Fruchtzwerg answer
this.Invoke((MethodInvoker)delegate
{
PopupNotifier pop = new PopupNotifier();
pop.TitleText = "Test";
pop.ContentText = "Hello World";
pop.Popup();
});
});