Allocate a console for a WinForm application(为 WinForm 应用程序分配控制台)
问题描述
我使用以下代码为 WinForm 应用程序分配控制台.控制台窗口成功显示并且输出在那里.但是当我关闭控制台窗口时,我的 WinForm 应用程序同时关闭.为什么?我想保留 WinForm 窗口.
I use the following code to allocate a Console for a WinForm application. The Console window shows up successfully and the output is there. But when I close the Console window, my WinForm applicaion is closed at the same time. Why? I want to keep the WinForm window.
private void btn_to_console_Click(object sender, EventArgs e)
{
if (NativeMethods.AllocConsole())
{
lbl_console_alloc_result.Text = "Console allocation successfully!";
IntPtr stdHandle = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE);
Console.WriteLine("from WinForm to Console!");
lbl_console_alloc_result.Text = Console.ReadLine();
}
else
lbl_console_alloc_result.Text = "Console allocation failed!";
}
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "GetStdHandle")]
public static extern System.IntPtr GetStdHandle(Int32 nStdHandle);
/// Return Type: BOOL->int
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "AllocConsole")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool AllocConsole();
提前谢谢...
推荐答案
关闭控制台窗口将关闭任何应用程序 - 无论是控制台应用程序、Windows 窗体、本机 Windows 应用程序还是 WPF 应用程序.这是控制台窗口的功能".
Closing a Console Window will shutdown any application -whether a console application, Windows Forms, native Windows app, or WPF application. This is a "feature" of Console windows.
如果您不希望这种行为,您应该改为创建一个自定义窗口来显示您的输出,而不是使用控制台窗口.否则,您需要调用 FreeConsole 而不是关闭将您的应用程序与控制台窗口分离的窗口.
If you don't want this behavior, you should, instead, just make a custom window to display your output instead of using a Console Window. Otherwise, you need to call FreeConsole instead of closing the Window to detach your application from the Console window.
这篇关于为 WinForm 应用程序分配控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为 WinForm 应用程序分配控制台


- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01