我如何判断用户是通过双击 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/