4

How do I disable echo in a windows console C application?

I don't really want to capture characters with _getch (I still want Ctrl-C) to work. Besides _getch only seems to disable echo for cmd but not in cygwin.

There must be a way to redirect the pipe or modify the console settings.

RunHolt
  • 1,892
  • 2
  • 19
  • 26

3 Answers3

8

Maybe SetConsoleMode (stolen from codeguru) :

#include <iostream>
#include <string>
#include <windows.h>


int main()
{
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    std::string s;
    std::getline(std::cin, s);

    std::cout << s << "\n";
    return 0;
}//main
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 1
    same idea used in [cross-platform code](http://code.google.com/p/xpost/source/browse/src/lib/xpost_compat.c#87) covers the windows case nicely. – luser droog Aug 28 '14 at 04:30
  • 2
    Here's an [updated link](https://github.com/luser-dr00g/xpost/blob/3063f60d342251754f5e78f454ffb5e69687fa9b/src/lib/xpost_compat.c#L132) for the above comment – Cogwheel May 15 '19 at 21:08
0

This is a stupid solution that I just come up with as the solutions above didn't work for me. Also using cygwin on Windows, with VS C++. This stupid solution "worked" for both windows cmd console and cygwin shell (at least I use putty to run cygwin shell, so your mileage may vary).

In my case, I wanted to read a character and process it, without echoing the character in the screen. So what I did was just print a backspace character, whitespace, and then another backspace character for every character input:

#include <conio.h>
...
printf("Your choice: ");
char cmd = ' ';
while (true) {
    cmd = _getche();
    printf("\b \b"); // this is the "magic"

    if (cmd == 'q') {
        printf("thanks for playing!\n");
        break;
    }
}

So you can type any invalid input that it won't just "show" in the console. It's far from a password input filter, but in cygwin shell it worked very well, and in Windows cmd console I could briefly see the key I pressed before it was erased.

Avenger
  • 177
  • 1
  • 8
0

Yes, the easiest way to do it my opinion would be to use freopen to basically change the file opened behind the stdout file descriptor.

You could redirect the console output to a file using

freopen("C:\some_file.txt", "w", stdout);

If you don't want to store the output at once, you should be able to write a /dev/null like (/dev/null is in Unix), but in windows (that I don't have you can try "nul" or "\Device\Null"

So something like the following should work :

freopen("\Device\Null", "w", stdout);

Sorry I can't actually try that out since I don't have windows, but that's the main idea.

AaronO
  • 495
  • 3
  • 7