2012-09-10 22 views
0

我正在寫一個提醒的小應用程序。爲此,我從stackoverflow網站上的類似問題&答案得到了很大的幫助。我使用雷霆提到的代碼中的鏈接描述 - 訪問 - How do I generate an alert at a specific time in C#? 代碼也被提及下文 -如何在C#中的特定時間隱藏和顯示錶單?

private void Form1_Load(object sender, EventArgs e) 
    { 
     System.Threading.TimerCallback callback = new   System.Threading.TimerCallback(ProcessTimerEvent); 
     var dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day , 10, 0, 0); 

     if (DateTime.Now < dt) 
     { 
      var timer = new System.Threading.Timer(callback, null, dt - DateTime.Now, TimeSpan.FromHours(24)); 
     this.Hide(); // This line works... Form hides itself 
     } 

    } 

    private void ProcessTimerEvent(object obj) 
    { 
     //MessageBox.Show("Hi Its Time"); 
     this.Show(); //This line does not work. Form gets disposed off instead of show 
    } 

我的問題 - 我得到的一切由雷霆(包括MessageBox中)提到的。但是,如果我嘗試在進行回調時隱藏表單並再次顯示而不是MessageBox.Show(「Hi Its Time」);這是行不通的。 Pl在每行上看到我的評論。我不明白爲什麼表單會被處置。

this.Visible() // does not work and disposed off the same way 

還嘗試通過更改其位置屬性將窗體移出屏幕。回來後,回到原來的位置,但這也行不通。我能做些什麼來隱藏&顯示返回的表單?

+0

我沒有得到你的代碼..它究竟是做什麼..? –

+0

您可以發佈您創建表單的其他代碼嗎? – sohil

回答

1

我相信你有一個交叉線程問題。你的回調應該是這樣的:

private void ProcessTimerEvent(object obj) 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke(new Action<object>(this.ProcessTimerEvent), obj); 
    } 
    else 
    { 
     this.Show(); 
    } 
} 
+0

或者使用System.Windows.Forms.Timer,它使用每個回調中窗體的同步上下文。 –

+0

感謝它幫助我 – Anand

0

我只是檢查,發現你的代碼收到此錯誤:

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

你只需要改變ProcessTimerEvent功能如下:

if (this.InvokeRequired) 
{ 
    this.BeginInvoke(new Action<object>(ProcessTimerEvent), obj); 

    // To wait for the thread to complete before continuing. 
    this.Invoke(new Action<object>(ProcessTimerEvent), obj); 
} 
else 
{ 
    this.Show(); 
} 
+0

爲什麼你建議雙重調用?您的評論爲「等待線程完成後再繼續」。在Invoke調用不正確之前。 –