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

前端 未结 6 603
闹比i
闹比i 2020-12-03 02:54

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

相关标签:
6条回答
  • 2020-12-03 03:14

    Environment.UserInteractive Property

    0 讨论(0)
  • 2020-12-03 03:14

    I haven't tested it, but Environment.UserInteractive looks promising.

    0 讨论(0)
  • 2020-12-03 03:14

    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 Enter before 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).

    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.

    0 讨论(0)
  • 2020-12-03 03:15

    To prompt for user input in an interactive console, but do nothing when run without a console or when input has been redirected:

    if (Environment.UserInteractive && !Console.IsInputRedirected)
    {
        Console.ReadKey();
    }
    
    0 讨论(0)
  • 2020-12-03 03:35

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

    bool is_console_app = Console.OpenStandardInput(1) != Stream.Null;
    
    0 讨论(0)
  • 2020-12-03 03:38

    A possible improvement of Glenn Slayden's solution:

    bool isConsoleApplication = Console.In != StreamReader.Null;
    
    0 讨论(0)
提交回复
热议问题