![](/img/trans.png)
[英]How can I select a row from the DataGridView equals textbox.Text after clicking a button by C# ?
[英]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.