C#:从控制台分离 [英] C#: Detach from console

查看:32
本文介绍了C#:从控制台分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 窗体应用程序,但当参数通过命令行传递时,它有时表现为无窗体(控制台应用程序).如果不传递任何参数,则它的行为与普通的 Windows 窗体一样.

当它作为控制台应用程序运行时,我使用 Console.WriteLine() 附加到控制台以输出消息.

[DllImport("kernel32.dll")]static extern bool AttachConsole(int input);static void Main(string[] args){if (args.Length == 0){Application.Run(new MyForm());}别的{//case args.Length >0附加控制台(-1);Console.WriteLine("启动我的无形应用...");new FormLessApp().Start();}}

但我不确定当无形应用程序完成时是否需要从控制台分离.有必要吗?如果是这样,我必须使用哪种 DLL 方法?

解决方案

FreeConsole 来自 Kernel32.dll.您可以在此处查看文档.

也根据文档:

<块引用>

进程可以使用 FreeConsole 函数将自身与其控制台分离.如果其他进程共享控制台,则控制台不会被销毁,但调用 FreeConsole 的进程无法引用它.当附加到控制台的最后一个进程终止或调用 FreeConsole 时,控制台将关闭.进程调用 FreeConsole 后,可以调用 AllocConsole 函数来创建新的控制台或 AttachConsole 来附加到另一个控制台.

因此我的猜测是,如果您打算在终止 FormLessApp() 进程时从控制台分离,则无需手动执行,它会自动销毁.>

I have a Windows Form application but it sometimes behaves as a formless (console application) when parameters are passed by command line. If no parameters are passed, then it behaves as a normal Windows Forms.

When it behaves as a console application, I attach to console to output messages using Console.WriteLine().

[DllImport("kernel32.dll")]
static extern bool AttachConsole(int input);

static void Main(string[] args)
{            
    if (args.Length == 0)
    {   
        Application.Run(new MyForm());
    }
    else 
    {
        // case args.Length > 0
        AttachConsole(-1);
        Console.WriteLine("Start my formless app...");
        new FormLessApp().Start();
    }
}

But I am not sure If I need to deatach from console when formless aplication finishes. Is it necessary? If so which DLL method do I have to use?

解决方案

FreeConsole from Kernel32.dll. You can see the documentation here.

Also according to the documentation:

A process can use the FreeConsole function to detach itself from its console. If other processes share the console, the console is not destroyed, but the process that called FreeConsole cannot refer to it. A console is closed when the last process attached to it terminates or calls FreeConsole. After a process calls FreeConsole, it can call the AllocConsole function to create a new console or AttachConsole to attach to another console.

Therefore my guess is, if you are planning to detach from the console when terminating the FormLessApp() process, you don't need to do it manually, it will be destroyed automatically.

这篇关于C#:从控制台分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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