Solved

How to loop until key is pressed...

Posted on 2004-09-08
12
731 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

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…
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…
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.
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…

932 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

12 Experts available now in Live!

Get 1:1 Help Now