C# 显示WPF-“;“通知图标”;分道扬镳
我目前正在使用office加载项,需要显示一个显示进度的通知对话框,我正在使用 我需要从一个单独的线程显示,因为我有很多代码已经在主线程上执行,这会导致wpf notifyicon阻塞并等待,因为windows消息队列中的消息没有被处理 我知道我应该在一个单独的线程上执行这个耗时的代码,并从主线程显示notifyicon并相应地更新它,但不幸的是,这不是一个替代方案,因为整个解决方案都是单线程的 例如:C# 显示WPF-“;“通知图标”;分道扬镳,c#,wpf,winforms,vsto,C#,Wpf,Winforms,Vsto,我目前正在使用office加载项,需要显示一个显示进度的通知对话框,我正在使用 我需要从一个单独的线程显示,因为我有很多代码已经在主线程上执行,这会导致wpf notifyicon阻塞并等待,因为windows消息队列中的消息没有被处理 我知道我应该在一个单独的线程上执行这个耗时的代码,并从主线程显示notifyicon并相应地更新它,但不幸的是,这不是一个替代方案,因为整个解决方案都是单线程的 例如: private FancyPopup fancyPopup; privat
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...";
}
更新
我已经能够使用此更新的代码进一步改进:
我正在一个新线程上创建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...";
}));
}
我已经解决了我的问题,我必须在单独的STA线程上初始化notifyIcon,并使用应用程序。运行以开始在该线程上发送windows消息
var myThread = new Thread(delegate()
{
notifyIcon = new NotifyIcon();
Application.Run();
});
myThread.SetApartmentState(ApartmentState.STA);
myThread.Start();
然后我必须调用通知对话框的UI。所有可视元素都应该从UI线程调用。你们应该把繁重的进程分成线程,这样UI线程就不会被阻塞。我已经更新了OP,请查看。