如何在程序执行时拥有控制台?

时间:2011-08-14 17:31:51

标签: c# winapi user-interface console

我正在尝试编写一个程序,它在控制台或GUI模式下工作,具体取决于执行参数。我设法编写了以下示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace wfSketchbook
{
    static class Program
    {
        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AttachConsole(int processId);

        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AllocConsole();

        [DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool FreeConsole();

        private const int ATTACH_PARENT_PROCESS = -1;

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                if (!AttachConsole(ATTACH_PARENT_PROCESS))
                    AllocConsole();
                Console.WriteLine("Welcome to console!");
                Console.ReadKey();
                FreeConsole();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
}

它通常有效,但是当从系统命令行调用程序时,cmd似乎不知道,该程序在控制台模式下工作并立即退出:

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>Welcome to console!

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>

我宁愿期待以下输出:

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>wfSketchbook.exe test

Welcome to console!

d:\Dokumenty\Dev\C#\Projekty\Win32\Sketchbook\wfSketchbook\bin\Debug>

我该如何纠正这个问题?

2 个答案:

答案 0 :(得分:3)

没有理想的解决方案。如果可以看到.exe是控制台模式应用程序,Cmd.exe将自动等待程序完成。对于您的应用,情况并非如此。一种解决方法是告诉它等待:

  

启动/等待yourapp.exe [参数]

另一种是始终使用AllocConsole()。它创建第二个控制台窗口的副作用。将应用程序类型更改为Console然后调用FreeConsole()也不理想,窗口的闪烁非常明显。选择你的毒药。

答案 1 :(得分:1)

没有任何可靠的方法可以将Windows应用程序变为控制台和GUI。您的程序是Windows应用程序 - 因此Windows会在控制台窗口之外启动 - 当程序启动时,您没有连接到控制台窗口。

您可以将项目输出更改为项目属性中的控制台应用程序。但是你总会得到一个控制台窗口。 Windows可以看到您的应用程序被标记为控制台应用程序,并在您运行之前创建了一个控制台。

有关详细信息和某些解决方法的链接,请参阅此blog post