• Advertisement

Archived

This topic is now archived and is closed to further replies.

Quick C++ question

This topic is 5097 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I test the keyboard for a keypress? I don''t want to have to wait for the user to enter something, just see if a key is being held down. I''m writing a console app, so no windows message queue available. Basically I am in a loop, I wait to see if a file exists, if so I act on it. I wanna test the keyboard to see if I need to quit. If no key press I wait a while then start the main loop again:
Loop {
  if (file exists)
      act on it
  wait 2 seconds
  if (key pressed)
     close down ports and dynamic classes/arrays then quit nicely
}
 

Share this post


Link to post
Share on other sites
Advertisement
1) #include <conio.h>

2) kbhit();

3) getch();

so for example:


#include <conio.h>

int main() {

int myChar = 0;
while(myChar != 27) { // while ESC was not pressed


//

// do something continuousely here

//


if(kbhit()) myChar = getch();
};
};


The only problem with this is that it''s 100% CPU usage

Share this post


Link to post
Share on other sites
That''s great, cheers.

The cpu usage is fine, I just check kbhit once at the end of the loop which contains a Sleep(2000) anyway.

Share this post


Link to post
Share on other sites
Not if there's a Sleep(2000) (or a sleep(2)) in there somewhere.

[edit: too slow! I blame the nachos.]

[edited by - fractoid on March 5, 2004 11:11:55 AM]

Share this post


Link to post
Share on other sites

  • Advertisement