Is it possible to build a Console app that does not display a console Window when double-clicked?

前端 未结 5 1404
余生分开走
余生分开走 2020-12-24 13:36

Related:
Should I include a command line mode in my applications?
How to grab parent process standard output?
Can a console application dete

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 13:52

    So, I've written tools with both a GUI and a CLI. The hard part was figuring out which one to open - in our case, though, the CLI version had required parameters, so I just opened the GUI if there weren't any parameters. Then, if they did want a console, call a function that looks something like:

    private const int ATTACH_PARENT_PROCESS = -1;
    private const int ERROR_INVALID_HANDLE = 6;
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AttachConsole(int dwProcessId);
    [DllImport("kernel32.dll")]
    static extern bool AllocConsole();
    [DllImport("kernel32.dll")]
    static extern bool FreeConsole();
    
    private static bool StartConsole()
    {
      if (!AttachConsole(ATTACH_PARENT_PROCESS)) // try connecting to an existing console  
      {  
          if (Marshal.GetLastWin32Error() == ERROR_INVALID_HANDLE) // we don't have a console yet  
          {  
              if (!AllocConsole()) // couldn't create a new console, either  
                  return false;  
          }
          else
              return false; // some other error
      }
      return true;
    }
    

    Returns whether the console was created. Don't forget to FreeConsole() when you're done!

    In our case, of course, if we don't create a console, we create a GUI. It'd be just as easy to create either a console or no UI, though.

    EDIT: That totally didn't answer the question in the edit that wasn't there when I started writing that, of course. Other than that our hack was just checking whether it was called with command-line parameters or not.

提交回复
热议问题