views:

143

answers:

3

I am trying to use the WINAPI ReadConsole() to wait for any keypress at the end of my Win32 console application.

CONSOLE_READCONSOLE_CONTROL tControl;
char pStr[65536];
DWORD dwBufLen = 1;
DWORD dwCtl;

tControl_c.nLength = sizeof( CONSOLE_READCONSOLE_CONTROL );
tControl_c.nInitialChars = 0;
tControl_c.dwControlKeyState = 0;
tControl_c.dwCtrlWakeupMask = NULL;

pBuf[0] = 0x00;

do
{
   ReadConsole( hConsole_c, pStr, (*pBufLen) * sizeof(TCHAR), pBufLen, &tControl );
}
while ( pStr[0] == 0x00 );

The code executes without throwing an exception. However, when the ReadConsole() function executes the error code ERROR_INVALID_HANDLE (0x06) is flagged. I have verified hConsole_c to be a valid handle. Does anyone have any insight as to what I am doing wrongly? I am using Visual C++ 2008 Express Edition. Thanks.

A: 

If you are just trying to wait for keypress at the end of your console app why dont you try System("Pause"); ?

SysAdmin
Yes, but I went to all the trouble of writing a wrapper class for the WINAPI Console functions. I'd like to use it. Do you have any suggestions for getting the above code to work?
Jim Fell
A: 

Your method of waiting for a keystroke is very over-complex. Using single C function calls, there are a couple of ways you can do this:

  • getch(); (or the ISO C++ conformant name, _getch), which is platform independent;
  • system("pause");, which is Windows-specific.
Saul Rennison
Yes, I have a working function that uses the ISO calls, but I went to all the trouble of writing a wrapper class for the WINAPI Console functions. I'd like to use it. Do you have any suggestions for getting the above code to work?
Jim Fell
+2  A: 

Works fine for me. The only way I could get it to fail with ERROR_INVALID_HANDLE was to pass it the STD_OUTPUT_HANDLE instead of the STD_INPUT_HANDLE. Are you sure hConsole_c is the input handle?

Luke
That was it. Thanks!
Jim Fell