簡體   English   中英

在 C# 中,如何在單擊 Windows 窗體中的按鈕后將某些內容打印到控制台?

[英]In C#, how can I print something to the console after clicking a button from Windows Form?

我正在使用 Visual Studio 2019 和 Windows 窗體(.NET Framework),我有一個帶有按鈕的 Windows 窗體。 單擊名為“btnPrint”的按鈕后,我想將某些內容打印到控制台。 我不知道該放什么代碼。

我試過 Console.WriteLine("Hello World!") 但沒有顯示控制台。 我等了幾分鍾,希望有什么東西出現,但這需要很長時間,所以我終止了程序。

這是我的代碼:

  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows.Forms;

  namespace Windows
  {
      public partial class Form1 : Form
      {
            public Form1()
            {
                 InitializeComponent();
            }

            private void btnPrint_Click(object sender, EventArgs e)
            {
                 Console.WriteLine("Hello World!");
            }
      }
   }

看起來您正在運行 Windows 窗體應用程序。 默認情況下,您嘗試使用Console.WriteLine()訪問的控制台不可用。 此命令僅適用於控制台應用程序(請參閱官方文檔的說明)。

如果您在 Visual Studio 中運行您的應用程序,您應該會看到Hello World! Visual Studio 的輸出窗口中的消息。

將輸出添加到代碼的一些方法:

分配控制台

如果您真的希望為您的表單應用程序打開一個控制台。 你可以看看這個答案 這將打開控制台,以便您可以使用它。 但是,如果關閉控制台,則整個應用程序都將關閉。

這是從上面鏈接的答案復制的代碼:

using System.Runtime.InteropServices;

private void Form1_Load(object sender, EventArgs e)
{
    // This will open up the console when the form is loaded.
    AllocConsole();
}

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();

富文本框

為您的 Form 應用程序獲取某種控制台的另一種方法是向表單本身添加一個輸出,如RichTextBox 並將您的消息寫入RichTextBox如下所示:

// Print the text
MyRichTextBox.AppendText("Hello World!\n" + output);
// Scroll the RichTextBox down
MyRichTextBox.ScrollToCaret();

調試日志

如果您將調試器(如 Visual Studio)附加到表單應用程序,您還可以使用System.Diagnostics Debug.WriteLine代替Console.WriteLine() 輸出將顯示在 Visual Studio 的輸出窗口中。

即使在您構建應用程序之后,這也將起作用。

控制台應用程序

您還可以創建一個控制台應用程序,以便控制台始終處於運行狀態。 在控制台應用程序中,您可以創建一個新表單來執行所有 From 交互。
這是一種解決方法,但它應該有效。

你應該做一個這樣的標簽,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Windows
{
    public partial class Form1 : Form
    {
        public Form1()
        {
                InitializeComponent();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
                Label Show_Text = new Label();
                Show_Text.Text = "Hello World!";
                Form1.Controls.Add(Show_Text);
        }
    }
}

有關 c# 標簽的其他首選項請參閱有關 c# 標簽的更多信息...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM