Write to console while waiting for input



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am a beginner in programming and I need to write a c# console app that does something (let's suppose writes stars to console) in a loop until user inputs a command like "stop".
Something like this:



While !('user entered word "stop"')
Console.Write("*")



The program should write stars independently of any user key presses or other commands, just do it's work until user writes exactly "stop" and presses Enter.
This:



string userinput = "";
while (true)
Console.Write("*");
userinput = Console.ReadLine();
if(userinput == "stop")
break;




is not a solution, because it will keep asking user for the input after each star printed.



Sorry if it's a stupid question, I can't even understand where to start.



EDIT:
Okay, it can be another task, like copying files or playing music or whatever, ANYTHING. I just can't understand how to constantly check the console for the
entered stop word without asking the user. Console can be blank, waiting for user input.










share|improve this question
























  • Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

    – MindSwipe
    Nov 16 '18 at 14:35







  • 3





    How can the user type while the console is busy with writing stars?

    – Rango
    Nov 16 '18 at 14:44











  • "How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

    – Александр Коржев
    Nov 16 '18 at 14:45







  • 1





    Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

    – John Wu
    Nov 16 '18 at 14:47






  • 2





    If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

    – Broom
    Nov 16 '18 at 14:50

















0















I am a beginner in programming and I need to write a c# console app that does something (let's suppose writes stars to console) in a loop until user inputs a command like "stop".
Something like this:



While !('user entered word "stop"')
Console.Write("*")



The program should write stars independently of any user key presses or other commands, just do it's work until user writes exactly "stop" and presses Enter.
This:



string userinput = "";
while (true)
Console.Write("*");
userinput = Console.ReadLine();
if(userinput == "stop")
break;




is not a solution, because it will keep asking user for the input after each star printed.



Sorry if it's a stupid question, I can't even understand where to start.



EDIT:
Okay, it can be another task, like copying files or playing music or whatever, ANYTHING. I just can't understand how to constantly check the console for the
entered stop word without asking the user. Console can be blank, waiting for user input.










share|improve this question
























  • Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

    – MindSwipe
    Nov 16 '18 at 14:35







  • 3





    How can the user type while the console is busy with writing stars?

    – Rango
    Nov 16 '18 at 14:44











  • "How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

    – Александр Коржев
    Nov 16 '18 at 14:45







  • 1





    Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

    – John Wu
    Nov 16 '18 at 14:47






  • 2





    If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

    – Broom
    Nov 16 '18 at 14:50













0












0








0








I am a beginner in programming and I need to write a c# console app that does something (let's suppose writes stars to console) in a loop until user inputs a command like "stop".
Something like this:



While !('user entered word "stop"')
Console.Write("*")



The program should write stars independently of any user key presses or other commands, just do it's work until user writes exactly "stop" and presses Enter.
This:



string userinput = "";
while (true)
Console.Write("*");
userinput = Console.ReadLine();
if(userinput == "stop")
break;




is not a solution, because it will keep asking user for the input after each star printed.



Sorry if it's a stupid question, I can't even understand where to start.



EDIT:
Okay, it can be another task, like copying files or playing music or whatever, ANYTHING. I just can't understand how to constantly check the console for the
entered stop word without asking the user. Console can be blank, waiting for user input.










share|improve this question
















I am a beginner in programming and I need to write a c# console app that does something (let's suppose writes stars to console) in a loop until user inputs a command like "stop".
Something like this:



While !('user entered word "stop"')
Console.Write("*")



The program should write stars independently of any user key presses or other commands, just do it's work until user writes exactly "stop" and presses Enter.
This:



string userinput = "";
while (true)
Console.Write("*");
userinput = Console.ReadLine();
if(userinput == "stop")
break;




is not a solution, because it will keep asking user for the input after each star printed.



Sorry if it's a stupid question, I can't even understand where to start.



EDIT:
Okay, it can be another task, like copying files or playing music or whatever, ANYTHING. I just can't understand how to constantly check the console for the
entered stop word without asking the user. Console can be blank, waiting for user input.







c# loops user-input






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 15:02







Александр Коржев

















asked Nov 16 '18 at 14:34









Александр КоржевАлександр Коржев

12




12












  • Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

    – MindSwipe
    Nov 16 '18 at 14:35







  • 3





    How can the user type while the console is busy with writing stars?

    – Rango
    Nov 16 '18 at 14:44











  • "How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

    – Александр Коржев
    Nov 16 '18 at 14:45







  • 1





    Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

    – John Wu
    Nov 16 '18 at 14:47






  • 2





    If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

    – Broom
    Nov 16 '18 at 14:50

















  • Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

    – MindSwipe
    Nov 16 '18 at 14:35







  • 3





    How can the user type while the console is busy with writing stars?

    – Rango
    Nov 16 '18 at 14:44











  • "How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

    – Александр Коржев
    Nov 16 '18 at 14:45







  • 1





    Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

    – John Wu
    Nov 16 '18 at 14:47






  • 2





    If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

    – Broom
    Nov 16 '18 at 14:50
















Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

– MindSwipe
Nov 16 '18 at 14:35






Just replace the while !(userinput) with while (true) as when the user types "stop" you'll break out of the loop

– MindSwipe
Nov 16 '18 at 14:35





3




3





How can the user type while the console is busy with writing stars?

– Rango
Nov 16 '18 at 14:44





How can the user type while the console is busy with writing stars?

– Rango
Nov 16 '18 at 14:44













"How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

– Александр Коржев
Nov 16 '18 at 14:45






"How can the user type while the console is busy with writing stars?" - That's what I'm trying to figure out.

– Александр Коржев
Nov 16 '18 at 14:45





1




1





Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

– John Wu
Nov 16 '18 at 14:47





Seems to me you need a way to check the keyboard input without blocking the program's execution. Perhaps check out the Console.KeyAvailable property.

– John Wu
Nov 16 '18 at 14:47




2




2





If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

– Broom
Nov 16 '18 at 14:50





If you don't want to wait for the user to hit enter between every star, what you are looking for requires multiple threads, and multiple console windows.

– Broom
Nov 16 '18 at 14:50












5 Answers
5






active

oldest

votes


















0














This will stop when the user presses any key



 while (!Console.KeyAvailable)

Console.Write("*");



This will only stop if the user presses Escape:



 while (true)

Console.Write("*");

if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)

break;




If you want the user to have to type multiple letters (like 'stop') you'll have to read all the keys they press and check whether the last four are 'stop'.






share|improve this answer






























    0














    Where he will write the input if console is used for printing stars in the same moment.
    You can make a loop to print stars until specific button from the keyboard is not pressed.
    After that you can make logic to save pressed keys into variable and loop until specific combination is not written. Don't forget to put Sleep in ur loop.
    Anyway writing stars and writing input in the same time is not a good idea.






    share|improve this answer
































      0














      There is a good answer here about reading input while not locking the main thread. You do so using Console.KeyAvailable and Console.ReadKey() in a separate thread.



      Writing back to the console at the same time is a little trickier. This would be easier if you let the user type blind (so they can't see what they've typed in). But the problems start when you want to show the user what they have typed, because you have to write the user input back to the console yourself (because you can't use Console.ReadLine() to do it for you). And, I presume, you don't want to end up with stars in the middle of their input, like:



      s*****t***o**p


      I assume you want something more like:



      ***********
      stop


      Which means you need to move the cursor around in the console to write the stars on one line and write the user input on another line.



      You should be able to do this with Console.SetCursorPosition to move the cursor up or down a line depending on which line you want to write on. But you will also have to keep track of how many characters you've written on each line so far.






      share|improve this answer
































        0














        you can use multi-threading to achieve this. With this, the main thread starts a background thread which will write stars until the person types stop and hits the enter key. It may however effect the way it is displayed since as you are typing, it will look like it is automatically adding the stars to the keys you have pressed but no worries, depending on your timer. When you hit the Enter key, it will not read the stars added previously.



        Below is a sample code for you to achieve what you want.



         using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading;
        using System.Threading.Tasks;

        namespace Practice

        class Program

        static bool write = true;
        static void Main(string args)

        //Write the stars using a background thread
        new Thread(() =>

        Thread.CurrentThread.IsBackground = true;
        WriteStars();
        ).Start();

        while (true)

        //Read the user input
        var input = Console.ReadLine();
        //Check the user input
        if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))

        write = false;
        Console.WriteLine("Finished. Program stopped!");
        Console.ReadKey();
        break;




        private static void WriteStars()

        while (write)

        Console.Write("*");

        //Make the thread wait for half a second
        Thread.Sleep(500);






        Thank you






        share|improve this answer























        • This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

          – Александр Коржев
          Nov 16 '18 at 15:20











        • You are most welcome

          – Conrad
          Nov 17 '18 at 13:08


















        0














        Here's a pretty high complexity solution. It's not looking for the word "stop", it's just prompting for a string (any string). It would be easy to adapt though.



        It polls the keyboard every 250 milliseconds for key input. If two seconds go by with no input, it outputs an asterisk. When you enter a character (or a backspace), it writes out the entire line (padded on the right with spaces), blanking out the existing asterisks.



        One thing it doesn't take care of is line wrap. If you let it be for long enough that the line fills with asterisks, then the console with wrap to the second line, and those asterisks will never be blanked out.



        I was surprised, but this actually feels like a reasonable UI. I'm not sure it's worth the added complexity, but...



         public static string GetString(string prompt)

        const int pollTime = 250; //milliseconds
        const int starTime = 8; //pollTime quantums (in this case 2 * 250 = 2000 ms)
        string buffer = string.Empty;
        Console.Write($"prompt: ");
        var top = Console.CursorTop;
        var left = Console.CursorLeft;
        //two loops,
        //outer loop is per character
        //the inner one causes a star to be output every 2 seconds,
        //it causes the keyboard to be polled every 1/4 second
        while (true) //this loop breaks with a return statement

        var noChar = true;
        var starLoopCount = 0;
        while (noChar && starLoopCount < starTime)

        if (Console.KeyAvailable)

        var keyRead = Console.ReadKey();
        if (keyRead.Key == ConsoleKey.Enter)

        OutputLine(left, top, buffer);
        return buffer;


        if (keyRead.Key == ConsoleKey.Backspace)

        if (buffer.Length > 0)

        buffer = buffer.Substring(0, buffer.Length - 1);
        OutputLine(left, top, buffer);
        noChar = false;
        continue;


        //otherwise, add the key to the buffer
        buffer += keyRead.KeyChar;
        OutputLine(left, top, buffer);
        noChar = false;
        starLoopCount = 0;

        ++starLoopCount;
        Thread.Sleep(pollTime);


        if (noChar)

        Console.Write("*");




        private static void OutputLine(int left, int top, string line)

        Console.SetCursorPosition(left, top);
        var blank = new string(' ', 80 - left - line.Length);
        Console.Write(line + blank);
        Console.SetCursorPosition(left + line.Length, top);






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339867%2fwrite-to-console-while-waiting-for-input%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          This will stop when the user presses any key



           while (!Console.KeyAvailable)

          Console.Write("*");



          This will only stop if the user presses Escape:



           while (true)

          Console.Write("*");

          if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)

          break;




          If you want the user to have to type multiple letters (like 'stop') you'll have to read all the keys they press and check whether the last four are 'stop'.






          share|improve this answer



























            0














            This will stop when the user presses any key



             while (!Console.KeyAvailable)

            Console.Write("*");



            This will only stop if the user presses Escape:



             while (true)

            Console.Write("*");

            if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)

            break;




            If you want the user to have to type multiple letters (like 'stop') you'll have to read all the keys they press and check whether the last four are 'stop'.






            share|improve this answer

























              0












              0








              0







              This will stop when the user presses any key



               while (!Console.KeyAvailable)

              Console.Write("*");



              This will only stop if the user presses Escape:



               while (true)

              Console.Write("*");

              if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)

              break;




              If you want the user to have to type multiple letters (like 'stop') you'll have to read all the keys they press and check whether the last four are 'stop'.






              share|improve this answer













              This will stop when the user presses any key



               while (!Console.KeyAvailable)

              Console.Write("*");



              This will only stop if the user presses Escape:



               while (true)

              Console.Write("*");

              if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape)

              break;




              If you want the user to have to type multiple letters (like 'stop') you'll have to read all the keys they press and check whether the last four are 'stop'.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 16 '18 at 14:55









              Robin BennettRobin Bennett

              1,880413




              1,880413























                  0














                  Where he will write the input if console is used for printing stars in the same moment.
                  You can make a loop to print stars until specific button from the keyboard is not pressed.
                  After that you can make logic to save pressed keys into variable and loop until specific combination is not written. Don't forget to put Sleep in ur loop.
                  Anyway writing stars and writing input in the same time is not a good idea.






                  share|improve this answer





























                    0














                    Where he will write the input if console is used for printing stars in the same moment.
                    You can make a loop to print stars until specific button from the keyboard is not pressed.
                    After that you can make logic to save pressed keys into variable and loop until specific combination is not written. Don't forget to put Sleep in ur loop.
                    Anyway writing stars and writing input in the same time is not a good idea.






                    share|improve this answer



























                      0












                      0








                      0







                      Where he will write the input if console is used for printing stars in the same moment.
                      You can make a loop to print stars until specific button from the keyboard is not pressed.
                      After that you can make logic to save pressed keys into variable and loop until specific combination is not written. Don't forget to put Sleep in ur loop.
                      Anyway writing stars and writing input in the same time is not a good idea.






                      share|improve this answer















                      Where he will write the input if console is used for printing stars in the same moment.
                      You can make a loop to print stars until specific button from the keyboard is not pressed.
                      After that you can make logic to save pressed keys into variable and loop until specific combination is not written. Don't forget to put Sleep in ur loop.
                      Anyway writing stars and writing input in the same time is not a good idea.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 16 '18 at 15:00

























                      answered Nov 16 '18 at 14:52









                      Beyond1337Beyond1337

                      33




                      33





















                          0














                          There is a good answer here about reading input while not locking the main thread. You do so using Console.KeyAvailable and Console.ReadKey() in a separate thread.



                          Writing back to the console at the same time is a little trickier. This would be easier if you let the user type blind (so they can't see what they've typed in). But the problems start when you want to show the user what they have typed, because you have to write the user input back to the console yourself (because you can't use Console.ReadLine() to do it for you). And, I presume, you don't want to end up with stars in the middle of their input, like:



                          s*****t***o**p


                          I assume you want something more like:



                          ***********
                          stop


                          Which means you need to move the cursor around in the console to write the stars on one line and write the user input on another line.



                          You should be able to do this with Console.SetCursorPosition to move the cursor up or down a line depending on which line you want to write on. But you will also have to keep track of how many characters you've written on each line so far.






                          share|improve this answer





























                            0














                            There is a good answer here about reading input while not locking the main thread. You do so using Console.KeyAvailable and Console.ReadKey() in a separate thread.



                            Writing back to the console at the same time is a little trickier. This would be easier if you let the user type blind (so they can't see what they've typed in). But the problems start when you want to show the user what they have typed, because you have to write the user input back to the console yourself (because you can't use Console.ReadLine() to do it for you). And, I presume, you don't want to end up with stars in the middle of their input, like:



                            s*****t***o**p


                            I assume you want something more like:



                            ***********
                            stop


                            Which means you need to move the cursor around in the console to write the stars on one line and write the user input on another line.



                            You should be able to do this with Console.SetCursorPosition to move the cursor up or down a line depending on which line you want to write on. But you will also have to keep track of how many characters you've written on each line so far.






                            share|improve this answer



























                              0












                              0








                              0







                              There is a good answer here about reading input while not locking the main thread. You do so using Console.KeyAvailable and Console.ReadKey() in a separate thread.



                              Writing back to the console at the same time is a little trickier. This would be easier if you let the user type blind (so they can't see what they've typed in). But the problems start when you want to show the user what they have typed, because you have to write the user input back to the console yourself (because you can't use Console.ReadLine() to do it for you). And, I presume, you don't want to end up with stars in the middle of their input, like:



                              s*****t***o**p


                              I assume you want something more like:



                              ***********
                              stop


                              Which means you need to move the cursor around in the console to write the stars on one line and write the user input on another line.



                              You should be able to do this with Console.SetCursorPosition to move the cursor up or down a line depending on which line you want to write on. But you will also have to keep track of how many characters you've written on each line so far.






                              share|improve this answer















                              There is a good answer here about reading input while not locking the main thread. You do so using Console.KeyAvailable and Console.ReadKey() in a separate thread.



                              Writing back to the console at the same time is a little trickier. This would be easier if you let the user type blind (so they can't see what they've typed in). But the problems start when you want to show the user what they have typed, because you have to write the user input back to the console yourself (because you can't use Console.ReadLine() to do it for you). And, I presume, you don't want to end up with stars in the middle of their input, like:



                              s*****t***o**p


                              I assume you want something more like:



                              ***********
                              stop


                              Which means you need to move the cursor around in the console to write the stars on one line and write the user input on another line.



                              You should be able to do this with Console.SetCursorPosition to move the cursor up or down a line depending on which line you want to write on. But you will also have to keep track of how many characters you've written on each line so far.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 16 '18 at 15:07

























                              answered Nov 16 '18 at 15:00









                              Gabriel LuciGabriel Luci

                              11.6k11525




                              11.6k11525





















                                  0














                                  you can use multi-threading to achieve this. With this, the main thread starts a background thread which will write stars until the person types stop and hits the enter key. It may however effect the way it is displayed since as you are typing, it will look like it is automatically adding the stars to the keys you have pressed but no worries, depending on your timer. When you hit the Enter key, it will not read the stars added previously.



                                  Below is a sample code for you to achieve what you want.



                                   using System;
                                  using System.Collections.Generic;
                                  using System.Linq;
                                  using System.Text;
                                  using System.Threading;
                                  using System.Threading.Tasks;

                                  namespace Practice

                                  class Program

                                  static bool write = true;
                                  static void Main(string args)

                                  //Write the stars using a background thread
                                  new Thread(() =>

                                  Thread.CurrentThread.IsBackground = true;
                                  WriteStars();
                                  ).Start();

                                  while (true)

                                  //Read the user input
                                  var input = Console.ReadLine();
                                  //Check the user input
                                  if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))

                                  write = false;
                                  Console.WriteLine("Finished. Program stopped!");
                                  Console.ReadKey();
                                  break;




                                  private static void WriteStars()

                                  while (write)

                                  Console.Write("*");

                                  //Make the thread wait for half a second
                                  Thread.Sleep(500);






                                  Thank you






                                  share|improve this answer























                                  • This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                    – Александр Коржев
                                    Nov 16 '18 at 15:20











                                  • You are most welcome

                                    – Conrad
                                    Nov 17 '18 at 13:08















                                  0














                                  you can use multi-threading to achieve this. With this, the main thread starts a background thread which will write stars until the person types stop and hits the enter key. It may however effect the way it is displayed since as you are typing, it will look like it is automatically adding the stars to the keys you have pressed but no worries, depending on your timer. When you hit the Enter key, it will not read the stars added previously.



                                  Below is a sample code for you to achieve what you want.



                                   using System;
                                  using System.Collections.Generic;
                                  using System.Linq;
                                  using System.Text;
                                  using System.Threading;
                                  using System.Threading.Tasks;

                                  namespace Practice

                                  class Program

                                  static bool write = true;
                                  static void Main(string args)

                                  //Write the stars using a background thread
                                  new Thread(() =>

                                  Thread.CurrentThread.IsBackground = true;
                                  WriteStars();
                                  ).Start();

                                  while (true)

                                  //Read the user input
                                  var input = Console.ReadLine();
                                  //Check the user input
                                  if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))

                                  write = false;
                                  Console.WriteLine("Finished. Program stopped!");
                                  Console.ReadKey();
                                  break;




                                  private static void WriteStars()

                                  while (write)

                                  Console.Write("*");

                                  //Make the thread wait for half a second
                                  Thread.Sleep(500);






                                  Thank you






                                  share|improve this answer























                                  • This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                    – Александр Коржев
                                    Nov 16 '18 at 15:20











                                  • You are most welcome

                                    – Conrad
                                    Nov 17 '18 at 13:08













                                  0












                                  0








                                  0







                                  you can use multi-threading to achieve this. With this, the main thread starts a background thread which will write stars until the person types stop and hits the enter key. It may however effect the way it is displayed since as you are typing, it will look like it is automatically adding the stars to the keys you have pressed but no worries, depending on your timer. When you hit the Enter key, it will not read the stars added previously.



                                  Below is a sample code for you to achieve what you want.



                                   using System;
                                  using System.Collections.Generic;
                                  using System.Linq;
                                  using System.Text;
                                  using System.Threading;
                                  using System.Threading.Tasks;

                                  namespace Practice

                                  class Program

                                  static bool write = true;
                                  static void Main(string args)

                                  //Write the stars using a background thread
                                  new Thread(() =>

                                  Thread.CurrentThread.IsBackground = true;
                                  WriteStars();
                                  ).Start();

                                  while (true)

                                  //Read the user input
                                  var input = Console.ReadLine();
                                  //Check the user input
                                  if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))

                                  write = false;
                                  Console.WriteLine("Finished. Program stopped!");
                                  Console.ReadKey();
                                  break;




                                  private static void WriteStars()

                                  while (write)

                                  Console.Write("*");

                                  //Make the thread wait for half a second
                                  Thread.Sleep(500);






                                  Thank you






                                  share|improve this answer













                                  you can use multi-threading to achieve this. With this, the main thread starts a background thread which will write stars until the person types stop and hits the enter key. It may however effect the way it is displayed since as you are typing, it will look like it is automatically adding the stars to the keys you have pressed but no worries, depending on your timer. When you hit the Enter key, it will not read the stars added previously.



                                  Below is a sample code for you to achieve what you want.



                                   using System;
                                  using System.Collections.Generic;
                                  using System.Linq;
                                  using System.Text;
                                  using System.Threading;
                                  using System.Threading.Tasks;

                                  namespace Practice

                                  class Program

                                  static bool write = true;
                                  static void Main(string args)

                                  //Write the stars using a background thread
                                  new Thread(() =>

                                  Thread.CurrentThread.IsBackground = true;
                                  WriteStars();
                                  ).Start();

                                  while (true)

                                  //Read the user input
                                  var input = Console.ReadLine();
                                  //Check the user input
                                  if (input.Equals("stop", StringComparison.OrdinalIgnoreCase))

                                  write = false;
                                  Console.WriteLine("Finished. Program stopped!");
                                  Console.ReadKey();
                                  break;




                                  private static void WriteStars()

                                  while (write)

                                  Console.Write("*");

                                  //Make the thread wait for half a second
                                  Thread.Sleep(500);






                                  Thank you







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 16 '18 at 15:11









                                  ConradConrad

                                  868




                                  868












                                  • This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                    – Александр Коржев
                                    Nov 16 '18 at 15:20











                                  • You are most welcome

                                    – Conrad
                                    Nov 17 '18 at 13:08

















                                  • This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                    – Александр Коржев
                                    Nov 16 '18 at 15:20











                                  • You are most welcome

                                    – Conrad
                                    Nov 17 '18 at 13:08
















                                  This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                  – Александр Коржев
                                  Nov 16 '18 at 15:20





                                  This "thread" thing seems to be the answer, I'll try it in the morning, thanks in advance.

                                  – Александр Коржев
                                  Nov 16 '18 at 15:20













                                  You are most welcome

                                  – Conrad
                                  Nov 17 '18 at 13:08





                                  You are most welcome

                                  – Conrad
                                  Nov 17 '18 at 13:08











                                  0














                                  Here's a pretty high complexity solution. It's not looking for the word "stop", it's just prompting for a string (any string). It would be easy to adapt though.



                                  It polls the keyboard every 250 milliseconds for key input. If two seconds go by with no input, it outputs an asterisk. When you enter a character (or a backspace), it writes out the entire line (padded on the right with spaces), blanking out the existing asterisks.



                                  One thing it doesn't take care of is line wrap. If you let it be for long enough that the line fills with asterisks, then the console with wrap to the second line, and those asterisks will never be blanked out.



                                  I was surprised, but this actually feels like a reasonable UI. I'm not sure it's worth the added complexity, but...



                                   public static string GetString(string prompt)

                                  const int pollTime = 250; //milliseconds
                                  const int starTime = 8; //pollTime quantums (in this case 2 * 250 = 2000 ms)
                                  string buffer = string.Empty;
                                  Console.Write($"prompt: ");
                                  var top = Console.CursorTop;
                                  var left = Console.CursorLeft;
                                  //two loops,
                                  //outer loop is per character
                                  //the inner one causes a star to be output every 2 seconds,
                                  //it causes the keyboard to be polled every 1/4 second
                                  while (true) //this loop breaks with a return statement

                                  var noChar = true;
                                  var starLoopCount = 0;
                                  while (noChar && starLoopCount < starTime)

                                  if (Console.KeyAvailable)

                                  var keyRead = Console.ReadKey();
                                  if (keyRead.Key == ConsoleKey.Enter)

                                  OutputLine(left, top, buffer);
                                  return buffer;


                                  if (keyRead.Key == ConsoleKey.Backspace)

                                  if (buffer.Length > 0)

                                  buffer = buffer.Substring(0, buffer.Length - 1);
                                  OutputLine(left, top, buffer);
                                  noChar = false;
                                  continue;


                                  //otherwise, add the key to the buffer
                                  buffer += keyRead.KeyChar;
                                  OutputLine(left, top, buffer);
                                  noChar = false;
                                  starLoopCount = 0;

                                  ++starLoopCount;
                                  Thread.Sleep(pollTime);


                                  if (noChar)

                                  Console.Write("*");




                                  private static void OutputLine(int left, int top, string line)

                                  Console.SetCursorPosition(left, top);
                                  var blank = new string(' ', 80 - left - line.Length);
                                  Console.Write(line + blank);
                                  Console.SetCursorPosition(left + line.Length, top);






                                  share|improve this answer



























                                    0














                                    Here's a pretty high complexity solution. It's not looking for the word "stop", it's just prompting for a string (any string). It would be easy to adapt though.



                                    It polls the keyboard every 250 milliseconds for key input. If two seconds go by with no input, it outputs an asterisk. When you enter a character (or a backspace), it writes out the entire line (padded on the right with spaces), blanking out the existing asterisks.



                                    One thing it doesn't take care of is line wrap. If you let it be for long enough that the line fills with asterisks, then the console with wrap to the second line, and those asterisks will never be blanked out.



                                    I was surprised, but this actually feels like a reasonable UI. I'm not sure it's worth the added complexity, but...



                                     public static string GetString(string prompt)

                                    const int pollTime = 250; //milliseconds
                                    const int starTime = 8; //pollTime quantums (in this case 2 * 250 = 2000 ms)
                                    string buffer = string.Empty;
                                    Console.Write($"prompt: ");
                                    var top = Console.CursorTop;
                                    var left = Console.CursorLeft;
                                    //two loops,
                                    //outer loop is per character
                                    //the inner one causes a star to be output every 2 seconds,
                                    //it causes the keyboard to be polled every 1/4 second
                                    while (true) //this loop breaks with a return statement

                                    var noChar = true;
                                    var starLoopCount = 0;
                                    while (noChar && starLoopCount < starTime)

                                    if (Console.KeyAvailable)

                                    var keyRead = Console.ReadKey();
                                    if (keyRead.Key == ConsoleKey.Enter)

                                    OutputLine(left, top, buffer);
                                    return buffer;


                                    if (keyRead.Key == ConsoleKey.Backspace)

                                    if (buffer.Length > 0)

                                    buffer = buffer.Substring(0, buffer.Length - 1);
                                    OutputLine(left, top, buffer);
                                    noChar = false;
                                    continue;


                                    //otherwise, add the key to the buffer
                                    buffer += keyRead.KeyChar;
                                    OutputLine(left, top, buffer);
                                    noChar = false;
                                    starLoopCount = 0;

                                    ++starLoopCount;
                                    Thread.Sleep(pollTime);


                                    if (noChar)

                                    Console.Write("*");




                                    private static void OutputLine(int left, int top, string line)

                                    Console.SetCursorPosition(left, top);
                                    var blank = new string(' ', 80 - left - line.Length);
                                    Console.Write(line + blank);
                                    Console.SetCursorPosition(left + line.Length, top);






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      Here's a pretty high complexity solution. It's not looking for the word "stop", it's just prompting for a string (any string). It would be easy to adapt though.



                                      It polls the keyboard every 250 milliseconds for key input. If two seconds go by with no input, it outputs an asterisk. When you enter a character (or a backspace), it writes out the entire line (padded on the right with spaces), blanking out the existing asterisks.



                                      One thing it doesn't take care of is line wrap. If you let it be for long enough that the line fills with asterisks, then the console with wrap to the second line, and those asterisks will never be blanked out.



                                      I was surprised, but this actually feels like a reasonable UI. I'm not sure it's worth the added complexity, but...



                                       public static string GetString(string prompt)

                                      const int pollTime = 250; //milliseconds
                                      const int starTime = 8; //pollTime quantums (in this case 2 * 250 = 2000 ms)
                                      string buffer = string.Empty;
                                      Console.Write($"prompt: ");
                                      var top = Console.CursorTop;
                                      var left = Console.CursorLeft;
                                      //two loops,
                                      //outer loop is per character
                                      //the inner one causes a star to be output every 2 seconds,
                                      //it causes the keyboard to be polled every 1/4 second
                                      while (true) //this loop breaks with a return statement

                                      var noChar = true;
                                      var starLoopCount = 0;
                                      while (noChar && starLoopCount < starTime)

                                      if (Console.KeyAvailable)

                                      var keyRead = Console.ReadKey();
                                      if (keyRead.Key == ConsoleKey.Enter)

                                      OutputLine(left, top, buffer);
                                      return buffer;


                                      if (keyRead.Key == ConsoleKey.Backspace)

                                      if (buffer.Length > 0)

                                      buffer = buffer.Substring(0, buffer.Length - 1);
                                      OutputLine(left, top, buffer);
                                      noChar = false;
                                      continue;


                                      //otherwise, add the key to the buffer
                                      buffer += keyRead.KeyChar;
                                      OutputLine(left, top, buffer);
                                      noChar = false;
                                      starLoopCount = 0;

                                      ++starLoopCount;
                                      Thread.Sleep(pollTime);


                                      if (noChar)

                                      Console.Write("*");




                                      private static void OutputLine(int left, int top, string line)

                                      Console.SetCursorPosition(left, top);
                                      var blank = new string(' ', 80 - left - line.Length);
                                      Console.Write(line + blank);
                                      Console.SetCursorPosition(left + line.Length, top);






                                      share|improve this answer













                                      Here's a pretty high complexity solution. It's not looking for the word "stop", it's just prompting for a string (any string). It would be easy to adapt though.



                                      It polls the keyboard every 250 milliseconds for key input. If two seconds go by with no input, it outputs an asterisk. When you enter a character (or a backspace), it writes out the entire line (padded on the right with spaces), blanking out the existing asterisks.



                                      One thing it doesn't take care of is line wrap. If you let it be for long enough that the line fills with asterisks, then the console with wrap to the second line, and those asterisks will never be blanked out.



                                      I was surprised, but this actually feels like a reasonable UI. I'm not sure it's worth the added complexity, but...



                                       public static string GetString(string prompt)

                                      const int pollTime = 250; //milliseconds
                                      const int starTime = 8; //pollTime quantums (in this case 2 * 250 = 2000 ms)
                                      string buffer = string.Empty;
                                      Console.Write($"prompt: ");
                                      var top = Console.CursorTop;
                                      var left = Console.CursorLeft;
                                      //two loops,
                                      //outer loop is per character
                                      //the inner one causes a star to be output every 2 seconds,
                                      //it causes the keyboard to be polled every 1/4 second
                                      while (true) //this loop breaks with a return statement

                                      var noChar = true;
                                      var starLoopCount = 0;
                                      while (noChar && starLoopCount < starTime)

                                      if (Console.KeyAvailable)

                                      var keyRead = Console.ReadKey();
                                      if (keyRead.Key == ConsoleKey.Enter)

                                      OutputLine(left, top, buffer);
                                      return buffer;


                                      if (keyRead.Key == ConsoleKey.Backspace)

                                      if (buffer.Length > 0)

                                      buffer = buffer.Substring(0, buffer.Length - 1);
                                      OutputLine(left, top, buffer);
                                      noChar = false;
                                      continue;


                                      //otherwise, add the key to the buffer
                                      buffer += keyRead.KeyChar;
                                      OutputLine(left, top, buffer);
                                      noChar = false;
                                      starLoopCount = 0;

                                      ++starLoopCount;
                                      Thread.Sleep(pollTime);


                                      if (noChar)

                                      Console.Write("*");




                                      private static void OutputLine(int left, int top, string line)

                                      Console.SetCursorPosition(left, top);
                                      var blank = new string(' ', 80 - left - line.Length);
                                      Console.Write(line + blank);
                                      Console.SetCursorPosition(left + line.Length, top);







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 16 '18 at 16:20









                                      Flydog57Flydog57

                                      2,3612812




                                      2,3612812



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339867%2fwrite-to-console-while-waiting-for-input%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Top Tejano songwriter Luis Silva dead of heart attack at 64

                                          政党

                                          天津地下鉄3号線