1

What i want:

An application, where there are a gui window and console window. Window can be clicked on, dragged, etcetera. At any given moment, console can be chosen, and a line entered, that will be processed.

What i already have:

An application, that allocates and attaches console to itself, then redirects standard streams to it. Code is:

AllocConsole() ;
AttachConsole( GetCurrentProcessId()); 
freopen("CONIN$","rb",stdin);   // reopen stdin handle as console window input

freopen("CONOUT$","wb",stdout);  // reopen stout handle as console window output

freopen("CONOUT$","wb",stderr); // reopen stderr handle as console window output

Then registers window class, creates and shows a window. Output into console works fine, interaction with window is correct.

However, i cannot input anything into console. I can make a guess about it: if i call something like std::cin >> my_string, i will be able to enter a line - but interaction with a window will stop until the input is completed. Is that correct? How can i make application behave in a way i described above?

update:

I have found related question: Test if stdin has input for C++ (windows and/or linux)

The code for determining, whether there are characters in console input was given there as follows:

bool StdinOpen() {
  static HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
  DWORD bytes_left;
  PeekNamedPipe(handle, NULL, 0, NULL, &bytes_left, NULL);
  return bytes_left;
}

However, it returns some exorbitant numbers, as if there always is input in console.

Community
  • 1
  • 1
Srv19
  • 3,458
  • 6
  • 44
  • 75

1 Answers1

0

I'd start by initializing the bytes_left variable and check the return value.

bool StdinOpen() {
  static HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
  DWORD bytes_left = 0;
  if (!PeekNamedPipe(handle, NULL, 0, NULL, &bytes_left, NULL))
     return false;
  return bytes_left != 0;
}
cdiggins
  • 17,602
  • 7
  • 105
  • 102