Aug 072008
 

gotoxy! what’s that?

gotoxy was one of my favorite functions in turbo c++, it moves the input cursor in a console application/MS-DOS application from one location to another.

So is there an equivalent function in a windows console application which does the same? Yes, it’s called SetConsoleCursorPosition.

Sample code

As always with me here is a function which does this!

BOOL gotoxy( const WORD x, const WORD y )
{
   COORD xy;
   xy.X = x;
   xy.Y = y;
   return SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), xy );
}
int main()
{
   if( !gotoxy( 10, 10 ))
   {
      std::cout < < "gotoxy failed :(, seems like coords are too big\n";       return 1;    }    return 0; }[/sourcecode] Result of calling "gotoxy", see how the pause message has shifted down and to the right.

Screenshot for gotoxy

Note that our gotoxy can fail if x or y is too big. A post from me will follow soon based on this function. It’s going to be about displaying a spining stick at the end of a progress message. You might have seen it if you have installed Linux.

Jun 222007
 

One option is to use

system( "cls" );

Another option is to to use this function. I copied this from MSDN.  😉

void cls( HANDLE hConsole )
{
   /* here's where we'll home the cursor */

   COORD coordScreen = { 0, 0 };

   BOOL bSuccess = FALSE;
   DWORD cCharsWritten = 0;

   /* to get buffer info */
   CONSOLE_SCREEN_BUFFER_INFO csbi = { 0 };

   /* number of character cells in the current buffer */
   DWORD dwConSize;

   /* get the number of character cells in the current buffer */
   bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );
   dwConSize = csbi.dwSize.X * csbi.dwSize.Y;

   /* fill the entire screen with blanks */
   bSuccess = FillConsoleOutputCharacter( hConsole,
				     ( TCHAR )' ',
				     dwConSize,
				     coordScreen,
				     &cCharsWritten );

   /* get the current text attribute */
   bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi );

   /* now set the buffer's attributes accordingly */
   bSuccess = FillConsoleOutputAttribute( hConsole,
				     csbi.wAttributes,
			              dwConSize,
				     coordScreen,
				     &cCharsWritten );
   /* put the cursor at (0, 0) */
   bSuccess = SetConsoleCursorPosition( hConsole, coordScreen );
   return;
}// End cls