为 WinForm 应用程序分配控制台

Allocate a console for a WinForm application(为 WinForm 应用程序分配控制台)
本文介绍了为 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 应用程序分配控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)