ReadLine () Callback

When a user enters a command into my console, I need to send it to the Java process (using StreamWriter) that I created. Is there a way to make a ReadLine callback, so when a user types something in the console, can I read it and then transfer it to my StreamWriter?

Pseudocode:

private void UserCommand(string text) { if(string.Equals(text, "save")) { inputWriter.WriteLine("/save-all"); } } 
0
source share
3 answers

Yes.

 string input = Console.ReadLine(); UserCommand(input); 
+1
source

Not directly. Unlike GUI programming, console programs are not event driven. You will have to explicitly call Console.ReadLine , which in turn blocks the current thread and waits until the user presses the Enter key. Then you can call your UserCommand .

If you want to do other things while waiting for user input, you will need to use at least two threads, one of which works, and one that is waiting for ReadLine return (and then calling any function that you want to call ...)

+1
source

You can use Console.OpenStandardInput to get the input stream and use the asynchronous stream functions.

  static string command = ""; static System.IO.Stream s; static bool quit = false; static byte[] buf = new byte[1]; static void Main(string[] args) { s = Console.OpenStandardInput(); s.BeginRead(buf, 0, 1, new AsyncCallback(s_Read), null); while (!quit) { // Do something instead of sleep System.Threading.Thread.Sleep(1000); Console.WriteLine("Sleeping"); } s.Close(); } public static void s_Read(IAsyncResult target) { if (target.IsCompleted) { int size = s.EndRead(target); string input = System.Text.Encoding.ASCII.GetString(buf); if (input.EndsWith("\n") || input.EndsWith("\r")) { if (command.ToLower() == "quit") quit = true; Console.Write("Echo: " + command); command = ""; } else command += input; s.BeginRead(buf, 0, 1, new AsyncCallback(s_Read), null); } } 
0
source

Source: https://habr.com/ru/post/1342016/


All Articles