Solved

How to loop until key is pressed...

Posted on 2004-09-08
12
737 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
  • 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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: 12013379
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

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…
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…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

831 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