2014-05-16 201 views
2

我有這個程序,其中我使用計時器重定向到另一個頁面。它可以工作,但問題是當我點擊取消按鈕時會出現一個消息框,當用戶不會點擊它並且計時器打勾時,messagebox沒有關閉。我怎樣才能自動關閉消息框?自動關閉消息框

這是什麼樣子..

enter image description here

,這裏是我用來重定向頁面

DispatcherTimer sessionTimer = new DispatcherTimer(); 
    public CashDepositAccount() 
    { 
     InitializeComponent(); 
     con = new SqlConnection(ConfigurationManager.ConnectionStrings["kiosk_dbConnectionString1"].ConnectionString); 
     con.Open(); 
     SqlCommand cmd1 = new SqlCommand("Select idle From [dbo].[Idle]", con); 
     idle = Convert.ToInt32(cmd1.ExecuteScalar()); 

     InputManager.Current.PreProcessInput += Activity; 
     activityTimer = new DispatcherTimer 
     { 
      Interval = TimeSpan.FromMinutes(idle), 
      IsEnabled = true 
     }; 
     activityTimer.Tick += Inactivity; 

    } 
    #region 

    void Inactivity(object sender, EventArgs e) 
    { 

     navigate = "Home"; 
     Application.Current.Properties["navigate"] = navigate; 

    } 

    void Activity(object sender, PreProcessInputEventArgs e) 
    { 


     activityTimer.Stop(); 
     activityTimer.Start(); 


    } 

我怎樣才能關閉消息框,當我重定向到代碼定時器打勾時的主頁?

+0

我假設你使用標準的'MessageBox.Show()'。您可能需要使用公共方法來滾動您自己的小對話窗口,以便在您的計時器到期時關閉它。 –

+0

我不能只使用標準的MessageBox.Show()? –

+2

你可以 - 通過一些WinAPI調用(發送WM_CLOSE到消息箱實例)。看到這裏:http://stackoverflow.com/a/19636437/1517578 –

回答

7

我已經使用此代碼來關閉消息框而不創建新窗體。它對我來說工作得很好。也可以幫助你們。我得到它Close a MessageBox after several seconds

private void btnOK_Click(object sender, RoutedEventArgs e) 
{ 
    AutoClosingMessageBox.Show("Wrong Input.", "LMS", 5000); 
} 

    public class AutoClosingMessageBox 
    { 
     System.Threading.Timer _timeoutTimer; 
     string _caption; 
     AutoClosingMessageBox(string text, string caption, int timeout) 
     { 
      _caption = caption; 
      _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, 
       null, timeout, System.Threading.Timeout.Infinite); 
      MessageBox.Show(text, caption); 
     } 

     public static void Show(string text, string caption, int timeout) 
     { 
      new AutoClosingMessageBox(text, caption, timeout); 
     } 

     void OnTimerElapsed(object state) 
     { 
      IntPtr mbWnd = FindWindow(null, _caption); 
      if (mbWnd != IntPtr.Zero) 
       SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); 
      _timeoutTimer.Dispose(); 
     } 
     const int WM_CLOSE = 0x0010; 
     [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] 
     static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 
     [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] 
     static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); 
    } 
+2

在這裏複製他人的答案並粘貼並不會讓你變得聰明。 http://stackoverflow.com/questions/14522540/close-a-messagebox-after-several-seconds –