问题描述
我正在使用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 Forms应用程序。默认情况下,您尝试使用<div [ngSwitch]="stepIndex">
<h1 *ngSwitchCase="1">Step 1</h1>
<h1 *ngSwitchCase="2">Step 2</h1>
...
</div>
<div class="button-container">
<button class="float-left" (click)="stepBackward()" >Back</button>
<button class="float-right" (click)="stepForward()">Next</button>
</div>
访问的控制台不可用。此命令仅适用于控制台应用程序(请参见the official documentation中的说明)。
如果在Visual Studio中运行应用程序,则应该在Visual Studio的输出窗口中看到Console.WriteLine()
消息。
一些将输出添加到代码中的方法:
AllocConsole
如果您确实希望为您的Forms应用程序打开控制台。您可以查看this answer。 这将打开控制台,以便您可以使用它。但是,如果关闭控制台,则会关闭整个应用程序。
这是从上面链接的答案中复制的代码:
Hello World!
RichTextBox
为您的Form应用程序获取控制台的另一种方法是将输出添加到表单本身,例如RichTextBox
。像这样将您的消息写到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();
:
RichTextBox
调试日志
如果将像Visual Studio这样的调试器附加到Form应用程序,也可以使用System.Diagnostics
中的// Print the text
MyRichTextBox.AppendText("Hello World!\n" + output);
// Scroll the RichTextBox down
MyRichTextBox.ScrollToCaret();
来代替Console.WriteLine()
。输出将显示在Visual Studio的输出窗口中。
即使您已经构建了应用程序,这也将起作用。
控制台应用程序
您还可以创建一个控制台应用程序,以便控制台始终处于启动状态。然后,在控制台应用程序中,您可以创建一个新表单来执行所有“发件人”交互。
这是一种解决方法,但应该可以。
您应该像这样制作一个标签
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#标签的其他偏好设置转到more about c# labels...