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

4

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


3个回答

10
将这个静态字段放在你的 "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 版本中获得了灵感


我添加了第二个字段 static bool startedFromVisualStudio = !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 && Environment.GetCommandLineArgs()[0].Contains("vshost");,以便在从VS启动时也等待按键。 - JCH2k

1

你可以尝试通过 P/Invoke 调用 Win32 GetStartupInfo() 函数来解决问题。

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

0

您可以查找父进程是什么:

    Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess()?.Parent()?.ProcessName);

其中Parent()是一个扩展方法,例如:

public static class Extensions
{
    private static string FindIndexedProcessName(int pid)
    {
        var processName = Process.GetProcessById(pid).ProcessName;
        var processesByName = Process.GetProcessesByName(processName);
        string processIndexdName = null;

        for (var index = 0; index < processesByName.Length; index++)
        {
            processIndexdName = index == 0 ? processName : processName + "#" + index;
            var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
            if ((int)processId.NextValue() == pid)
            {
                return processIndexdName;
            }
        }

        return processIndexdName;
    }

    private static Process FindPidFromIndexedProcessName(string indexedProcessName)
    {
        var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
        return Process.GetProcessById((int)parentId.NextValue());
    }

    public static Process Parent(this Process process)
    {
        return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接