2016-03-22 60 views
2

我想知道如何自動顯示Windows窗體應用程序中的通知。winforms通知

我的代碼在這裏:

cn.Open(); 
SqlCommand cmd = new SqlCommand("select Count(*) from Issue where Return_Date < @Date", cn); 
cmd.Parameters.AddWithValue("@Date",DateTime.Now); 
int NumberOfOverdue = (int)cmd.ExecuteScalar(); 
cn.Close(); 

if (NumberOfOverdue > 0) 
{ 
    notifyIcon1.ShowBalloonTip(500, "Library Management System", "There are " + NumberOfOverdue + " overdued book", ToolTipIcon.Warning); 
} 

的代碼位於INT的,顯然它後,才啓動程序觸發;但我希望通知在if條件中的要求自動滿足之後立即顯示。

+0

那麼你應該將通知使用類似於[計時器](https://msdn.microsoft.com/en-us/library/system.timers.timer(v = vs.110).aspx)的內容來檢查您的狀況並顯示通知 – Pikoh

+0

「只在我之後觸發啓動程序「我不明白你在這裏想說什麼。當然你必須在Form_Load運行之前啓動程序... – Zack

+0

不清楚。你什麼時候想要它來?爲什麼不在加載程序後顯示它,這確實是你不必按任何鍵的地方 – ehh

回答

2

雖然詹姆斯開發提到SqlDepency類是一個好辦法,你也可以簡單地用一個Timer這樣的:

public partial class Form1 : Form 
{ 
    private Timer _timer; 
    private string _connectionString; // set this to your connection string 
    public Form1() 
    { 
     InitializeComponent(); 
     _timer = new Timer() 
     { 
      Enabled = true, 
      Interval = 2000 // interval in milliseconds 
     }; 

     _timer.Tick += _timer_Tick; 
    } 

    private void _timer_Tick(object sender, EventArgs e) 
    { 
     using(SqlConnection cn = new SqlConnection(_connectionString)) 
     { 
      cn.Open(); 
      using(
       SqlCommand cmd = 
        new SqlCommand("select Count(*) from Issue where Return_Date < @Date", cn)) 
      { 
       cmd.Parameters.AddWithValue("@Date", DateTime.Now); 
       int NumberOfOverdue = (int)cmd.ExecuteScalar(); 

       if (NumberOfOverdue > 0) 
       { 
        notifyIcon1.ShowBalloonTip(500, "Library Management System", 
               "There are " + NumberOfOverdue + " overdued book", 
               ToolTipIcon.Warning); 
       } 
      } 
     } 
    } 
} 

Timer提高其Tick事件(approximatly)每2秒(您可以通過以毫秒爲單位輸入Interval屬性來選擇時間)。在事件處理程序_timer_Tick中,您可以執行sql請求並在必要時顯示通知。

我更改了一下代碼,使用using語句而不是手動關閉/處理對象。

一定要選擇Interval明智:

  • 如何立刻你需要通過這個請求產生的
  • 多少網絡流量/數據庫負載
相關問題