如何确定程序终止后是否关闭DOS控制台

时间:2011-07-10 08:50:21

标签: .net console-application

当我运行我的控制台应用程序时,它会显示一些输出,我希望用户看到它。另外,我的程序必须以高架模式运行。

因此,当用户从非提升的命令提示符运行它时,将显示标准对话框,其中用户接受提升运行它。问题是为此创建了一个新的控制台窗口,并在程序终止后立即关闭。我想留下来让用户阅读输出。

简单,对吧?只需在代码末尾添加Console.ReadLine()即可。但是,当从提升的提示符运行时,没有创建新的控制台,但用户必须按一个键让应用程序退出 - 这很烦人。

我的问题:是否有可能知道控制台窗口将在应用程序终止时关闭,这样我才可以执行Console.ReadLine()

感谢。

1 个答案:

答案 0 :(得分:2)

你需要一些小的pinvoke才能发现这一点。 GetConsoleProcessList()api函数返回附加到控制台的进程列表。如果您的程序从另一个进程继承控制台,那将超过1。使它看起来类似于:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            if (OwnsConsole()) {
                Console.Write("Press ENTER to exit");
                Console.ReadLine();
            }
        }
        public static bool OwnsConsole() {
            int[] pids = new int[1];   // NOTE: intentionally too short
            int retval = GetConsoleProcessList(pids, pids.Length);
            if (retval == 0) throw new System.ComponentModel.Win32Exception();
            return retval == 1;
        }
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern int GetConsoleProcessList(int[] pids, int arraySize);

    }
}
相关问题