如何确定控制台应用程序的启动方式?

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

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

 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版本中得到了这个想法。

您可以通过P /调用Win32 GetStartupInfo()函数来解决它。

 [DllImport("kernel32", CharSet=CharSet.Auto)] internal static extern void GetStartupInfo([In, Out] STARTUPINFO lpStartupInfo);