2010-08-20 102 views
4

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

+2

[Win32控制台应用程序是否可以检测是否已从资源管理器运行?](http://stackoverflow.com/questions/510805/can-a-win32-console-application-detect-如果-IT-过气 - 运行 - 从 - - 探险家或否) – joshuapoehls 2010-08-20 01:25:16

回答

1

您可能可以通过P /调用Win32 GetStartupInfo()函数来计算出结果。

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

棒在你的“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 version of this question得到了主意。

+0

我加入了第二场'静态布尔startedFromVisualStudio = \t \t \t \t!Console.IsOutputRedirected \t \t \t \t &&!Console.IsInputRedirected \t \t \t \t &&!Console.IsErrorRedirected \t \t \t \t && Environment.UserInteractive \t \t \t \t && Environment.CurrentDirectory == System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly()位置) \t \t \t \t && Console.CursorTop == 0 && Console.CursorLeft == 0 \t \t \t \t && Environment.GetCommandLineArgs()[0] .Contains(“vshost”);'当从VS启动时也等待按键 – JCH2k 2016-08-03 09:33:20

相关问题