C# Windows 控制台应用程序如何判断它是否以交互方式运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1188658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:22:32  来源:igfitidea点击:

How can a C# Windows Console application tell if it is run interactively

c#console-applicationuser-interaction

提问by Jeff Leonard

How can a Windows console application written in C# determine whether it is invoked in a non-interactive environment (e.g. from a service or as a scheduled task) or from an environment capable of user-interaction (e.g. Command Prompt or PowerShell)?

用 C# 编写的 Windows 控制台应用程序如何确定它是在非交互式环境(例如从服务或作为计划任务)还是从能够进行用户交互的环境(例如命令提示符或 PowerShell)中调用?

采纳答案by Arsen Mkrtchyan

回答by Michael Stum

I haven't tested it, but Environment.UserInteractivelooks promising.

我还没有测试过,但Environment.UserInteractive看起来很有希望。

回答by Glenn Slayden

To determine if a .NET application is running in GUI mode:

要确定 .NET 应用程序是否在 GUI 模式下运行:

bool is_console_app = Console.OpenStandardInput(1) != Stream.Null;

回答by C. Augusto Proiete

If all you're trying to do is to determine whether the console will continue to exist after your program exits (so that you can, for example, prompt the user to hit Enterbefore the program exits), then all you have to do is to check if your process is the only one attached to the console. If it is, then the console will be destroyed when your process exits. If there are other processes attached to the console, then the console will continue to exist (because your program won't be the last one).

如果您要做的只是确定程序退出后控制台是否会继续存在(例如,以便您可以Enter在程序退出之前提示用户点击),那么您所要做的就是检查您的进程是否是唯一附加到控制台的进程。如果是,那么当您的进程退出时控制台将被销毁。如果有其他进程附加到控制台,那么控制台将继续存在(因为您的程序不会是最后一个)。

For example*:

例如*:

using System;
using System.Runtime.InteropServices;

namespace CheckIfConsoleWillBeDestroyedAtTheEnd
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // ...

            if (ConsoleWillBeDestroyedAtTheEnd())
            {
                Console.WriteLine("Press any key to continue . . .");
                Console.ReadKey();
            }
        }

        private static bool ConsoleWillBeDestroyedAtTheEnd()
        {
            var processList = new uint[1];
            var processCount = GetConsoleProcessList(processList, 1);

            return processCount == 1;
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern uint GetConsoleProcessList(uint[] processList, uint processCount);
    }
}

(*) Adapted from code found here.

(*) 改编自此处找到的代码。

回答by Theodor Zoulias

A possible improvement of Glenn Slayden's solution:

Glenn Slayden 解决方案的可能改进:

bool isConsoleApplication = Console.In != StreamReader.Null;