我目前正在开发一个 Office 加载项,我需要显示一个显示进度的通知对话框,我正在使用Philipp Sumi 的 wpf-notifyicon http://www.codeproject.com/Articles/36468/WPF-NotifyIcon.
我需要显示通知图标 http://www.codeproject.com/Articles/36468/WPF-NotifyIcon来自单独的线程,因为我有很多代码已经在主线程上执行,这会导致 wpf-notifyicon 阻塞并等待,因为 Windows 消息队列中的消息没有被处理。
我知道我应该在单独的线程上执行这段耗时的代码,并从主线程显示通知图标并相应地更新它,但不幸的是这不是替代方案,因为整个解决方案是单线程的。
Example:
private FancyPopup fancyPopup;
private void button1_Click(object sender, EventArgs e)
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon = Resources.Led;
fancyPopup = new FancyPopup();
Thread showThread = new Thread(delegate()
{
notifyIcon.ShowCustomBalloon(fancyPopup, System.Windows.Controls.Primitives.PopupAnimation.Fade, null);
});
showThread.Start();
}
private void button2_Click(object sender, EventArgs e)
{
fancyPopup.TextB.Text = "Doing something...";
//Keep the main thread busy.
Thread.Sleep(5000);
fancyPopup.TextB.Text = "Done doing something...";
}
Update我已经能够通过这个更新的代码取得进一步的进展:
我正在新线程上创建 TaskbarIcon 对象,并使用 Application.Run 处理该线程上的应用程序消息循环...
private FancyPopup fancyPopup;
private void button1_Click(object sender, EventArgs e)
{
Thread showThread = new Thread(delegate()
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon = Resources.Led;
fancyPopup = new FancyPopup();
notifyIcon.ShowCustomBalloon(fancyPopup, System.Windows.Controls.Primitives.PopupAnimation.Fade, null);
System.Windows.Forms.Application.Run();
});
showThread.SetApartmentState(ApartmentState.STA);
showThread.Start();
}
private void button2_Click(object sender, EventArgs e)
{
fancyPopup.Dispatcher.Invoke(new Action(delegate
{
fancyPopup.TextB.Text = "Doing something...";
}));
//Keep the main thread busy.
Thread.Sleep(5000);
fancyPopup.Dispatcher.Invoke(new Action(delegate
{
fancyPopup.TextB.Text = "Done doing something...";
}));
}