我有一个运行新线程的应用程序来显示任务栏图标。现在我无法弄清楚如何从主线程中调用TaskbarIcon(这是在新线程上创建的)以显示气球提示。
我现在的代码是:
public class NotificationHelper
{
private TaskbarIcon notifyIcon { get; set; }
public NotificationHelper()
{
Thread thread = new Thread(OnLoad);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
}
public void ShowNotification(string text)
{
notifyIcon.ShowBalloonTip("Demo", text, notifyIcon.Icon);
}
public void OnLoad()
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon =
new Icon(@".\Icon\super-man-icon.ico");
//notifyIcon.ToolTipText = "Left-click to open popup";
notifyIcon.Visibility = Visibility.Visible;
while (true)
{
Thread.Sleep(1000);
}
}
private void ShowBalloon()
{
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}
}
当我试着打电话给ShowNotification时(" foobar");'我得到了这个例外:
Object reference not set to an instance of an object.
我有' while(true){}' in' Onload()'是我需要线程运行,直到我关闭我的应用程序。
答案 0 :(得分:1)
在主线程中,使用以下命令创建一个调度程序:
Dispatcher dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
将其传递给您的NotificationHelper:
Dispatcher FDispatcher;
public NotificationHelper(Dispatcher ADispatcher)
{
FDispatcher = ADispatcher;
//...
}
显示气球:
private void ShowBalloon()
{
FDispatcher.invoke(new Action(() => {
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}));
}
答案 1 :(得分:0)
您可以尝试锁定notifyIcon并检查null,如下所示:
public class NotificationHelper
{
private readonly object notifyIconLock = new object();
private TaskbarIcon notifyIcon { get; set; }
public NotificationHelper()
{
Thread thread = new Thread(OnLoad);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
}
public void ShowNotification(string text)
{
lock (notifyIconLock)
{
if (notifyIcon != null)
{
notifyIcon.ShowBalloonTip("Demo", text, notifyIcon.Icon);
}
}
}
public void OnLoad()
{
lock (notifyIconLock)
{
notifyIcon = new TaskbarIcon();
notifyIcon.Icon =
new Icon(@".\Icon\super-man-icon.ico");
//notifyIcon.ToolTipText = "Left-click to open popup";
notifyIcon.Visibility = Visibility.Visible;
}
}
private void ShowBalloon()
{
lock (notifyIconLock)
{
if (notifyIcon != null)
{
notifyIcon.ShowBalloonTip("Demo", Message, notifyIcon.Icon);
}
}
}
}