簡體   English   中英

C# 控制台應用程序:有沒有辦法檢測 exe 是否從命令行運行?

[英]C# Console Application: Is there a way to detect whether the exe was run from a command line or not?

如果我從現有命令行 window 運行我的Program.exe ,那么當它完成並退出時,控制台 Output 仍然存在並且可以查看。

如果我只是雙擊我的Program.exe ,那么它將打開一個新的命令行 window,用於控制台 Output ......但是當我的 exe 完成時,window 將關閉,輸出。

在后一種情況下,為了防止 output 日志丟失,我可能希望Main()的最后兩行是Console.WriteLine("Press any key to exit"); Console.ReadKey(); Console.WriteLine("Press any key to exit"); Console.ReadKey();

但如果我在前一種情況下這樣做,那就有點煩人了。

有什么方法可以檢測這兩種情況之間的差異,以便我可以有條件地“等待用戶說我可以關閉”......僅在必要時?

如果您想檢查您的應用程序是否從 .NET 中的命令行啟動,您可以使用Console.GetCursorPosition() 這樣做的原因是,當您從命令行啟動它時,cursor 會從初始點 ( (0, 0) ) 移開,因為您在終端中輸入了一些內容(應用程序的名稱)。 您可以通過相等性檢查來做到這一點:

// .NET 6
class Program
{
    public static void Main(string[] args)
    {
        if (Console.GetCursorPosition() == (0, 0))
        {
            //something GUI
        }
        else
        {
            //something not GUI
        }
    }
}

注意:您必須將 output 類型設置為 Console Application,因為其他 output 類型將使Console.GetCursorPosition()拋出異常。

對於從命令行運行控制台應用程序並從 Visual Studio 運行它的情況, Process.GetCurrentProcess().MainWindowTitle為空。 在這些情況下,您不需要額外的Console.ReadLine()

在 Windows Explorer 中雙擊運行它時,window 標題是 exe 的路徑。 在這種情況下,您確實需要額外的Console.ReadLine()

所以一個有點老套的方法(我只測試了上面的三種情況!)可能是將它添加到Main()的末尾:

if (!string.IsNullOrEmpty(Process.GetCurrentProcess().MainWindowTitle))
    Console.ReadLine();

我不會在生產代碼中使用它,但它可以用作測試實用程序等的快速破解。

在.Net5之前:

if (Console.Title == System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
{
    //Title in Explorer (and VS) contains path + filename
    Console.WriteLine("Executed in Explorer");
    Console.ReadLine();
}

if (Console.Title.Contains("Command Prompt"))
    Console.WriteLine("Executed in a 'Command Prompt'");

if (Console.Title.Contains("PowerShell"))
    Console.WriteLine("Executed in PowerShell");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM