使用C#后台工作者调用“烤面包机”弹出窗口无法正常工作

时间:2013-09-13 16:19:45

标签: c# wpf multithreading popup backgroundworker

我对C#很陌生,而且我正在开发一个WPF应用程序,该应用程序具有长时间连接Web服务的后台进程。 当我从Web服务中获取某些代码时,我将启动方法。我有所有工作,但一个人创建一个“烤面包机”弹出消息。 我创建了一个表单作为烤面包机弹出窗口。我的问题是它是从backroundWorker线程调用的,它只执行一次,它不会向上滑动屏幕。用于升起屏幕的计时器功能不会运行。为简单起见,我使用了之前回答的问题的代码:

public partial class Form1 : Form
{
    private Timer timer;
    private int startPosX;
    private int startPosY;

    public Form1()
    {
        InitializeComponent();
        // We want our window to be the top most
        TopMost = true;
        // Pop doesn't need to be shown in task bar
        ShowInTaskbar = false;
        // Create and run timer for animation
        timer = new Timer();
        timer.Interval = 50;
        timer.Tick += timer_Tick;
    }

    protected override void OnLoad(EventArgs e)
    {
        // Move window out of screen
        startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width;
        startPosY = Screen.PrimaryScreen.WorkingArea.Height;
        SetDesktopLocation(startPosX, startPosY);
        base.OnLoad(e);
        // Begin animation
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        //Lift window by 5 pixels
        startPosY -= 5; 
        //If window is fully visible stop the timer
        if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height)
            timer.Stop();
        else
           SetDesktopLocation(startPosX, startPosY);
    }
}

然后在我的bgWorker_DoWork方法中,我有:

    var dict = new JavaScriptSerializer().Deserialize<Dictionary<string,
object>>(responseFromServer);
int notifyType = (int)dict["notificationType"];
switch (notifyType)
{ 
   case 6:
         Debug.WriteLine(responseFromServer);  Form1 popup = new Form1();
         popup.Show();
         break; 
    default:
         Debug.WriteLine(responseFromServer);
         break; 
}

成为C#的新手我不知道如何保持定时器方法的执行,直到烤面包机信息完全显示。

或者有更好的方法来实现这个toast popup然后表单吗?

请帮帮忙? 谢谢。

1 个答案:

答案 0 :(得分:0)

你不能依赖这个工作,因为它使用的是另一个线程 您需要将弹出窗口的创建分配到主UI线程


抱歉误读了问题并提出了Winform解决方案。已更新!

使用Control.Invoke

    public Form1()
    {
        InitializeComponent();

    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
       /* this.Invoke((Action)(() =>
                        {
                            var form2 = new Form2();
                            form2.Show();
                        }));  Winforms Method*/
         Dispatcher.Invoke((Action)(() =>
                        {
                            var form2 = new Form2();
                            form2.Show();
                        }));

    }

    private void Form1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

实际上,您可以在单独的线程上创建窗口。网上有很多关于如何做到这一点的教程。但请记住,控件只能在创建它们的线程上访问。