Make your own free website on Tripod.com
 
« February 2007 »
S M T W T F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
You are not logged in. Log in

Programming Tips
Tuesday, 13 February 2007
getch and getche in Windows console apps!!
Mood:  mischievious
Topic: VC++

Ever wondered how to implement getch and getche in Windows console application...

Here is how we do this...

int getch()
{
    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
    if( hStdIn == INVALID_HANDLE_VALUE )
    {
        return 0;
    }// End if

    DWORD dwInputMode = 0;
    GetConsoleMode( hStdIn, &dwInputMode );

    // Code that disables line input and echoing of entered character
    SetConsoleMode( hStdIn, dwInputMode & ~ENABLE_LINE_INPUT &
                                          ~ENABLE_ECHO_INPUT );

    char cBuff = 0;
    DWORD dwBytesRead = 0;
    if( !ReadFile( hStdIn, &cBuff, sizeof( cBuff ), &dwBytesRead, 0 ))
    {
        return 0;
    }

    // Return to previous settings
    SetConsoleMode( hStdIn, dwInputMode );

    return cBuff;
}// End getch

int getche()
{
    HANDLE hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
    if( hStdOut != INVALID_HANDLE_VALUE )
    {
        char cGetCh = getch();
        DWORD dwBytesWritten = 0;
        WriteFile( hStdOut, &cGetCh, sizeof( cGetCh ), &dwBytesWritten, NULL );
       
        return cGetCh;
    }// End if
   
    return 0;
}// End getche


Posted by Nibu babu thomas at 1:38 PM
Updated: Tuesday, 13 February 2007 2:10 PM

Thursday, 15 February 2007 - 5:52 PM

Name: "Friend"

Nice work nibu.

View Latest Entries