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

我与影子孤独终老i 提交于 2019-11-30 01:50:11
Martin Beckett

See Can a Win32 console application detect if it has been run from the explorer or not?

Or I think the official way is to check the parent process is cmd.exe or explorer.exe

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.

Just build it as a Windows Forms app, but don't give it a GUI. Unfortunately then you won't get any console output when it's run from the command line either... is that a problem?

Jan

I haven't read everything thru, but did this (a little while ago, more testing needed):

DWORD proc[2],procsfound=GetConsoleProcessList(proc,ELEMS(proc));
if (procsfound>1)
// I'm started as a command in cmd.exe
else
// started from explorer or other non-console parent

IFF there's more than one proc attached, I need to restore the console which I manipulated, otherwise not. May be useful, at least it's simplicity itself. Start the code from VS will yield a single attached proces, running it from commandprompt did activate the branch to clean up my mess. Btw, a console launched from explorer or other non-console app will have a zero-length title?

Aaron Hoffman

Would this be more like a Service then?

OR

What About a Windows Forms application that doesn't have a visible form? It would still show up in the Task Manager Processes list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!