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 应用程序分配控制台
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01