Search code examples
c#.nettextterminalconsole

How to disable non-intended user input in the terminal C#


When i write a infinite loop that doesn't have any behaviour on its body, the user still have the possibility to write text at it, even without calling any input function:

Note: I'm using Linux, Manjaro. .NET 8; Shell: zsh

using System;

namespace Program;

public class UserInputTest
{
    public static void Main()
    {
        // user input is not disabled
        while (true) {}
    }
}

If i start to type on my keyboard some letters, they will be visible in the terminal. How can i disable that behaviour?

(Note: I know that a infinite loop isn't useful, but it's only an example of my problem.)

I already tried to close the input or output streams, but it not worked:

Console.In.Close();
Console.Out.Close();

Console.OpenStandardInput().Close();
Console.OpenStandardOutput().Close();

Solution

  • I fixed it by launching a process with the Linux command stty [echo | -echo] (echo to enable, -echo to disable). It enables/disables the echoing of the character inputed by the user.

    ProcessStartInfo info = new("/bin/bash")
    {
        Arguments = $"-c \"stty -echo\"",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false,
        CreateNoWindow = true
    };
    
    Process process = new()
    {
        StartInfo = info
    };
    
    process.Start();
    process.WaitForExit();