我使用的是Visual Studio 2019和Windows窗体(.NET Framework(,我有一个带有按钮的Windows窗体。单击名为"btnPrint"的按钮后,我想将某些内容打印到控制台。我不知道该放什么代码。
我试过控制台。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中运行应用程序,您应该在Visual Studio的输出窗口中看到Hello World!
消息。
一些将输出添加到代码中的方法:
AllocConsole
如果您确实希望为您的Forms应用程序打开控制台。你可以看看这个答案。这将打开控制台,以便您可以使用它。但是,如果关闭控制台,整个应用程序将关闭。
这是代码,复制自上面链接的答案:
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();
Rich文本框
为Form应用程序获得控制台的另一种方法是向窗体本身添加输出,如RichTextBox
。然后把你的信息写到RichTextBox
上,就像这样:
// Print the text
MyRichTextBox.AppendText("Hello World!n" + output);
// Scroll the RichTextBox down
MyRichTextBox.ScrollToCaret();
调试日志
如果将Visual Studio之类的调试器附加到Form应用程序,则也可以使用System.Diagnostics
中的Debug.WriteLine
来代替Console.WriteLine()
。输出将显示在Visual Studio的输出窗口中。
即使在构建了应用程序之后,这也会起作用。
控制台应用程序
您还可以创建一个控制台应用程序,以便控制台始终处于运行状态。然后,在Console应用程序中,您可以创建一个新的Form来执行所有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标签的信息。。。