SoFunction
Updated on 2025-03-01

How to hide console keyboard input in C#

This article describes the method of hiding the keyboard input of the console in C#. Share it for your reference. The details are as follows:

using System;
namespace RobvanderWoude
{
 class HideInput
 {
  static int Main( string[] args )
  {
   try
   {
    bool clearscreen = false;
    if (  > 1 )
    {
     return WriteError( "Too many command line arguments" );
    }
    if (  == 1 )
    {
     switch ( args[0].ToUpper( ) )
     {
      case "/C":
       clearscreen = true;
       break;
      case "/?":
       return WriteError( );
      default:
       return WriteError( "Invalid command line argument \"" + args[0] + "\"" );
     }
    }
    // Set console foreground color to background color to hide what's being typed
    ConsoleColor color = ;
     = ;
    // Read 1 line of input from the console
    string input = ( );
    // Restore the original console foreground color
     = color;
    // Clear the screen id specified on the command line
    if ( clearscreen )
    {
     ( );
    }
    // Display the input - which should be redirected for this program to be of any use
    ( input );
    // Returncode 0 for success, or 1 if the input was empty or whitespace only
    if ( ( input ) )
    {
     return 1;
    }
    else
    {
     return 0;
    }
   }
   catch ( Exception e )
   {
    return WriteError(  );
   }
  }
  public static int WriteError( string errorMessage = "" )
  {
   ( );
   if ( ( errorMessage ) == false )
   {
    ( );
     = ;
    ( "ERROR: " );
     = ;
    ( errorMessage );
    ( );
   }
   ( );
   ( "HideInput, Version 1.10" );
   ( "Batch utility to read 1 line of input while hiding what's being typed, by" );
   ( "temporarily setting the console foreground color equal to its background color" );
   ( );
   ( "Usage: FOR /F \"tokens=*\" %%A IN ('" );
    = ;
   ( "HIDEINPUT" );
   ( );
   ( "') DO SET password=%%A" );
   ( "  or: FOR /F \"tokens=*\" %%A IN ('" );
    = ;
   ( "HIDEINPUT /C" );
   ( );
   ( "') DO SET password=%%A" );
   ( );
   ( "Where: " );
    = ;
   ( "/C" );
   ( );
   ( " clears the screen to remove what's typed from the screen buffer" );
   ( );
   ( "Written by Rob van der Woude" );
   return 1;
  }
 }
}

I hope this article will be helpful to everyone's C# programming.