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

前端 未结 6 618
闹比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

    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.

提交回复
热议问题