문제

C#에 작성된 Windows 콘솔 애플리케이션은 비 중과 환경 (예 : 서비스 또는 예정된 작업) 또는 사용자 상호 작용이 가능한 환경 (예 : 명령 프롬프트 또는 PowerShell)에서 호출되는지 여부를 어떻게 결정할 수 있습니까?

도움이 되었습니까?

해결책

다른 팁

.NET 응용 프로그램이 GUI 모드에서 실행 중인지 확인하기 위해 :

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

나는 그것을 테스트하지 않았지만 환경 .userinteractive 유망한 것 같습니다.

프로그램 종료 후 콘솔이 계속 존재하는지 여부를 결정하는 것입니다. Enter 프로그램이 종료되기 전에), 그러면 프로세스가 콘솔에 연결된 유일한 프로세스인지 확인하는 것입니다. 그렇다면 프로세스가 종료 될 때 콘솔이 파괴됩니다. 콘솔에 첨부 된 다른 프로세스가있는 경우 콘솔이 계속 존재합니다 (프로그램이 마지막이 아니기 때문에).

예를 들어*:

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);
    }
}

(*) 발견 된 코드에서 조정되었습니다 여기.

Glenn Slayden의 솔루션 개선 가능성 :

bool isConsoleApplication = Console.In != StreamReader.Null;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top