Solved

How to loop until key is pressed...

Posted on 2004-09-08
12
728 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
 
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now