分配控制台的WinForm应用程序 [英] Allocate a console for a WinForm application

查看:138
本文介绍了分配控制台的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();



谢谢...

Thanks in advance...

推荐答案

关闭控制台窗口将关闭任何应用程序 - 无论是一个控制台应用程序,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应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆