Mohammed B.
Mohammed B.

Reputation: 170

Console Application Console window - Visual C++

I have made a C++ code in visual studio, a console application. My question is how to make the final exe run without console ( a process only seen from task manager )

The solutions I have seen till now all make the console appear for a second then go out. I don't want this. Don't appear at all.

is there any option or flag in visual studio to do this? ( something like -mwindows flag in g++ )

Thank's in advance

Upvotes: 2

Views: 1361

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44181

In the Project Properties on the Configuration Properties->Linker->System page, you need to set the value of SubSystem to Windows (/SUBSYSTEM:WINDOWS). The default for a new console application project is Console (/SUBSYSTEM:CONSOLE), which causes Windows to allocate a new console or attach to the parent process's console when starting your program.

enter image description here


You also need to change your main function to be WinMain. The signature for `WinMain is:

int CALLBACK WinMain(
  _In_ HINSTANCE hInstance,
  _In_ HINSTANCE hPrevInstance,
  _In_ LPSTR     lpCmdLine,
  _In_ int       nCmdShow)
{
    // Your code here
}

With the above approach, child console processes will still create console windows. Since you stated in a comment that you want to use popen, you can't really easily use the normal way of calling CreateProcess with SW_HIDE.

What you really want to do is to attach a hidden console window to your process and allow your child processes to inherit it. This probably isn't the best code, but here's a way to do it:

// Allocates a hidden console window for this process. This console can be
// inherited by child console processes, preventing them from creating a
// visible console. Returns false if the attempt fails.
bool AllocHiddenConsole()
{
  TCHAR command[] = _T("cmd.exe");
  STARTUPINFO startupInfo{};
  PROCESS_INFORMATION processInfo{};
  startupInfo.cb = sizeof(startupInfo);
  startupInfo.dwFlags = STARTF_USESHOWWINDOW;
  startupInfo.wShowWindow = SW_HIDE;

  if (!CreateProcess(NULL, command, NULL, NULL, FALSE,
    CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo))
  {
    return false;
  }

  bool attached = false;
  for (int i = 0; i < 1000; i++)
  {
    if (AttachConsole(processInfo.dwProcessId))
    {
      attached = true;
      break;
    }
    Sleep(10);
  }

  TerminateProcess(processInfo.hProcess, 0);
  CloseHandle(processInfo.hProcess);
  CloseHandle(processInfo.hThread);

  return attached;
}

Upvotes: 2

Related Questions