2015-09-23 52 views
2

我想知道如何在對話框中打印字符串。我不想在控制檯中輸出字符串。 所以我有這樣的代碼:在對話框中輸出字符串

private void info_Click(object sender, EventArgs e) 
{    
    // Solution Exxplorer Rechtsklick add text file 
    string line = System.IO.File.ReadAllText("Bedienungsanleitung.txt"); 
    Console.Write(line); 
} 

我已經嘗試型動物的解決方案,我在互聯網上找到。 任何人都可以告訴我我需要什麼對話嗎?

+1

如果是'WinForms','MessageBox.Show(線);'可能? – ASh

回答

1

如果文本不是很多,可以使用MessageBox,否則,如果文本太多,應該使用自定義對話框。

using System.Windows.Forms; 
... 
private void info_Click(object sender, EventArgs e) 
{ 
    string line = System.IO.File.ReadAllText("Bedienungsanleitung.txt"); // Solution Exxplorer Rechtsklick add text file 

    MessageBox.Show(line); 
} 
+0

如果它是一個控制檯應用程序,您首先需要添加System.Windows.Form引用。 – Bgl86

+1

好點。由於他的例子看起來像一個單擊事件處理程序,我認爲它不是控制檯應用程序。 – Joe

2

如果你是在一個控制檯應用程序的工作首先你必須System.Windows.Forms的你solution.To添加引用做到這一點,你可以使用參照子文件夾中的解決方案資源管理器,右鍵單擊它然後單擊添加引用。在那裏選擇框架,在此選項卡下,您將看到System.Windows.Forms並選擇它。

enter image description here

你這樣做去後回到代碼,然後把這個在類的頂部,你可以看到using語句

using System.Windows.Forms; 

在MessageBox.Show(),我可以看到有21種不同的方式(重載)在.Net Framework 4.5中使用.Show()方法,也可能在其他版本中。這意味着您可以自定義。一個採用全簽名我更喜歡使用是

MessageBox.Show( 「信息」, 「對話框的標題」,MessageBoxButtons, MessageBoxIcon);

在這裏你可以看到一個有效的例子

 MessageBox.Show("Do you need to save before exit ?","Select the Option",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question); 

相關MessageBox的另一個重要的事實是的DialogResult。我們可以使用這個來檢查代碼中的條件。

 private void Exit() 
     { 
      DialogResult answer= null; 

      answer = MessageBox.Show("Are you sure that you need to quit ?\nAll unsaved data will be lost.","Exit Confirmation!",MessageBoxButtons.YesNo,MessageBoxIcon.Question); 

      if (answer == DialogResult.Yes) 
      { 
       //Do something if the user wants to exit 
      } 
      else 
      { 
       //Do something if user don't want to exit 

      } 
     } 

的輸出,就會像這樣

enter image description here