Solved

How to loop until key is pressed...

Posted on 2004-09-08
12
759 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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 100 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 25 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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

726 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