2014-01-25 33 views
1

如果條件不滿足,我需要顯示一個消息框然後停止我的程序,我該怎麼做?如果條件不符合,停止應用程序啓動

現在我有這樣的:

private void MainForm_Load(object sender, EventArgs e){ 
    if(condition == false){ 
     MessageBox.Show("Condition not met. Program will now close!"); 
     Application.Exit(); 
    } 
    new window.ShowDialog(); 
} 

但是當我運行它,新的窗口閃爍很簡單,程序關閉。

回答

2

我沒有表現出一個新的對話框,我剛剛從關閉的MainForm了下他們,如果他們沒有被授權。 This.Close立即退出程序。

private void MainForm_Load(object sender, EventArgs e) 
{ 
    //some code here 
    if (condition == false) 
    { 
     MessageBox.Show("Condition not met. Program will now close!"); 
     //i log the user logged in 
     this.Close(); 
    } 
    else 
    { 
     //continue to setup the form 
    } 
} 
+0

謝謝,這個工程。 – user2705775

1

你在調用Application.Exit();只是在顯示對話框之後,而不必等待查看dialogresult返回的內容。這就是爲什麼它閃爍和消失。

試試這個。

DialogResult result = MessageBox.Show("Condition not met. Program will now close!", "Confirmation", messageBoxButtons.YesNoCancel); 
if(result == DialogResult.Yes) 
    //... 
else if (result == DialogResult.No) 
    //... 
else 
    //... 
+0

通過對話框閃爍,我的意思是「new dialog.ShowDialog();」。我應該說得更好。 – user2705775

+0

這似乎不是需要是/否確認的消息類型。 –

1

使用一個else塊:

private void MainForm_Load(object sender, EventArgs e){ 
    if(condition == false){ 
     MessageBox.Show("Condition not met. Program will now close!"); 
     Application.Exit(); 
    } 
    else { 
     new dialog.ShowDialog(); 
    } 
} 

Application.Exit不會立即退出應用程序。它導致消息循環結束,但您的代碼仍然完成運行MainForm_Load方法。

+0

當我使用else語句時,表單會短暫閃爍。我怎樣才能隱藏它? – user2705775

+0

@ user2705775使用具有特定條件的elseif –

1

您不想處理啓動窗體的Load事件,因爲啓動窗體已在該階段顯示。你想把代碼放在你的Main方法中,這是創建啓動表單的地方。以下是主要方法,在Program.cs文件,貌似默認:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 
} 

您只需環繞那些三行代碼的「if」語句。 Application.Run調用會阻塞,直到它傳遞的表單關閉,此時Main方法完成並且您的應用程序退出。如果您沒有進行該Application.Run調用,那麼Main方法會立即完成,並且應用程序會關閉而無需創建,而不必介意顯示一個啓動窗體。

+0

謝謝,我會盡力回覆你。 – user2705775

+0

我不認爲我能做到這一點,因爲我的情況依賴主窗體上的COM端口。 – user2705775

+0

我從來沒有惹過Program類,不是我不能,只是從來沒有任何我在其他地方無法完成的事情。 – wruckie

1

用途:

private void MainForm_Load(object sender, EventArgs e){ 
    if(condition == false){ 
     MessageBox.Show("Condition not met. Program will now close!"); 
     Environment.Exit(0);// or Application.Exit(); 

    } else { 
    new dialog.ShowDialog(); 
    } 
} 
+0

當我使用else語句時,表單會短暫閃爍。我怎樣才能隱藏它? – user2705775

相關問題