?
Solved

How to loop until key is pressed...

Posted on 2004-09-08
12
Medium Priority
?
765 Views
Last Modified: 2012-05-05
I have a loop:

While True
...
End While

Which runs indefinately until i close the program.  How can I change the loop so that it will run until i press a key?  I tried "Do While console.readline() is nothing" but that seems to block execution of the loop.  Suggestions?
0
Comment
Question by:stealth188
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +2
12 Comments
 
LVL 4

Expert Comment

by:andrewpk
ID: 12011768
you could simply capture a keypress event in a procedure, and set  StopNow = True

your loop will be based on StopNow being false, as soon as the key is pressed, this condition is false and next execution will stop the loop

andrew
0
 
LVL 1

Author Comment

by:stealth188
ID: 12011777
I'm being dense.  Can you give me an example?
0
 
LVL 4

Expert Comment

by:andrewpk
ID: 12011815
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
          {
               
               if(e.KeyCode==Keys.Return)
                    Console.WriteLine("return");

               if(e.Control)
                    Console.WriteLine("control");
          }

that's a sample keypress capture  (just search   keypress event for more examples)

change   Console.WriteLine("control");  to do something like this
StopNow = True


private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
          {
               
               if(e.KeyCode==Keys.Return)
                    StopNow = True

}

just change that to whichever key you want, and you're home free

andrew
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:stealth188
ID: 12011850
Thanks for that example.  The problem that I seem to be having (again being dense) is that i'm running a console app and dont have any way to fire an event for a keypress (or click).
0
 
LVL 4

Expert Comment

by:andrewpk
ID: 12011991
i'm not really sure how to capture it within a console app....
0
 
LVL 10

Expert Comment

by:heintalus
ID: 12012126
You could always set a low level Keyboard hook & set it to kill your app when a certain Keysequence is pressed.

Take a look at this

http://www.developer.com/net/net/article.php/11087_2193301_3

HTH
Andy
0
 
LVL 1

Author Comment

by:stealth188
ID: 12012567
The trick is that I just want to exit the loop so i can gather/disply some statistics about what the loop has been doing.  Thanks for the input.  I'm hoping there is an easier way...  I was thinking along the lines of the old QBasic InKey$.
0
 
LVL 18

Expert Comment

by:armoghan
ID: 12014061
Ohh I think there could be another better way of doing it..

Create a Thread which takes the input only and make the loop in the main thread, as soon as the thread gets the input pass it to the while loop
0
 
LVL 1

Author Comment

by:stealth188
ID: 12017268
I'm following you in concept, but still a bit fuzzy on the details.  Could you share some psudo code?
0
 
LVL 18

Accepted Solution

by:
armoghan earned 400 total points
ID: 12024152
This is code in C#, you can easliy convert it into VB.NET
and if you find any problem I will do it for you

/// <summary>
      /// Summary description for Class1.
      /// </summary>
      class Class1
      {
            System.Threading.Thread t;
            bool hit = false;
            int ch =0;
            public Class1()
            {
                  while(!kbhit())
                  {
                        System.Threading.Thread.Sleep(1000);
                        Console.Out.WriteLine("Press <Enter> to stop this printing.");
                  }
            Console.Out.WriteLine("" + ch);
            }
            public bool kbhit()
            {
                  if(t == null)
                  {
                        t = new System.Threading.Thread(new
                              System.Threading.ThreadStart(run));
                        t.Start();            
                  }      
                  return hit;
            }
            public void run()
            {
                  try
                  {
                        ch = Console.Read() ;
                        hit = true;
                  }
                  catch(Exception e)
                  {
                  Console.Out.WriteLine(      e.Message);
                  }
            }

      /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                  new Class1();      
                        
                        
            }
      
      
      }


0
 
LVL 4

Assisted Solution

by:Javert93
Javert93 earned 100 total points
ID: 12029979
The problem with Console.Read() is that the user still has to press <Enter> before it will return, rather than when the user presses a key. In fact, the only difference between Read() and ReadLine() is that Read() reads the input one character at a time, while ReadLine() reads the entire line. Either way, if there is no input waiting, both functions block until the user types something and presses <Enter>. Howeve, you can use the Win32 console API's to read a single character input without the user having to press <Enter>. In fact a wonder person by the name of Tim Sneath has written a class that extends the capabilities of the console to perform functions like clearing the console, changing screen colors, and yes... reading input a single character at a time. You can find his code mode at http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=b76d1f08-2d79-47bd-825b-0489938aae0f.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question