首页 新闻 会员 周边

c# timer 弹出窗体

0
悬赏园豆:50 [已解决问题] 解决于 2014-08-27 15:11

我需要实现一个功能,每1分钟请求一次服务器,如果服务器有消息则弹出消息窗体。

我尝试代码如下:

private static System.Timers.Timer CheckNotificationTimer = new System.Timers.Timer();

public MainForm()
{
InitializeComponent();
CheckNotificationTimer.Interval = 2000;
CheckNotificationTimer.Enabled = true;
CheckNotificationTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckNotificationTimer_Elapsed); CheckNotificationTimer.AutoReset = true; }

private static void CheckNotificationTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{

NotificationForm form = new NotificationForm();
int x = Screen.PrimaryScreen.WorkingArea.Right - form.Width;
int y = Screen.PrimaryScreen.WorkingArea.Bottom - form.Height;
form.Location = new Point(x, y);
form.Show();
//KryptonMessageBox.Show("xxx")
}

 

当执行弹出NotificationForm 时,NotificationForm 是卡死的,貌似是线程阻塞了,我应该怎样实现这样的功能需求呢?

谢谢

cwcls的主页 cwcls | 初学一级 | 园豆:27
提问于:2014-08-06 16:50
< >
分享
最佳答案
1

使用Backgroundworker组件,然后用下面的两个事件来操作

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
             //1、这里做很复杂的事情,这个里面可以把线程暂停掉,不会影响到界面的操作的,可以用下面的方法来实现timer的暂停时间控制
             Thread.Sleep(1000);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //2、做完后会调用这个事件




            //3、下面的代码可以帮助你实现循环调用
            backgroundWorker1.RunWorkerAsync();
        }
收获园豆:25
刘宏玺 | 专家六级 |园豆:14020 | 2014-08-08 22:09
其他回答(2)
3

请用Backgroundworker

XiaoFaye | 园豆:3087 (老鸟四级) | 2014-08-06 18:16
0

采用委托的方式弹窗。

private delegate void Test();

private readonly Timer timer = new Timer { Enabled = true, Interval = 3000 };
private Alert alert;

public Form1()
{
InitializeComponent();
timer.Elapsed += timer_Elapsed;
}

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new Test(ShowBox));
}
}

private void ShowBox()
{
if (alert == null)
{
alert = new Alert();
}
alert.Show();
}

Alert是一个新窗体。
收获园豆:25
幻天芒 | 园豆:37175 (高人七级) | 2014-08-06 19:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册