c# - 您如何确定控制台应用程序是如何启动的?

标签 c# .net command-line console console-application

我如何判断用户是通过双击 EXE(或快捷方式)启动了我的控制台应用程序,还是他们已经打开了命令行窗口并在该 session 中执行了我的控制台应用程序?

最佳答案

将此静态字段粘贴到您的“程序”类中,以确保它在任何输出之前运行:

static bool StartedFromGui = 
         !Console.IsOutputRedirected
      && !Console.IsInputRedirected
      && !Console.IsErrorRedirected
      && Environment.UserInteractive
      && Environment.CurrentDirectory == System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
      && Console.CursorTop == 0 && Console.CursorLeft == 0
      && Console.Title == Environment.GetCommandLineArgs()[0]
      && Environment.GetCommandLineArgs()[0] == System.Reflection.Assembly.GetEntryAssembly().Location;

这有点矫枉过正/偏执狂,但是从资源管理器启动时选择不响应 cls && app.exe(通过检查完整路径)甚至 cls && "f:\ull\path\to\app.exe"(通过查看标题)。

我的想法来自 win32 version of this question .

关于c# - 您如何确定控制台应用程序是如何启动的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3527555/

相关文章:

windows - 用于打印图片的命令行工具?

c# - 尝试删除条目时接收 System.IO.IOException

c# - ClientScript 不适用于 AJAX UpdateProgress

c# - 2 ASP.NET MVC 中的 View 模型

c# - 重新抛出包装对象的异常

SVN:有没有办法将文件标记为 "do not commit"?

c# - VS MSTest runner 在内存测试中运行时锁定 System.Data.SQLite.dll

c# - asp.net mvc Razor 额外空间

iphone - MonoTouch - System.Reflection.Emit.ModuleBuilder 错误

linux - 从命令行在 Linux 中连接 OpenDocument 文本文件