We help IT Professionals succeed at work.

Getting keyboard input while working

razvanl
razvanl asked
on
Hi,

I have a C program working on Unix and I need a way to detect keystrokes while the program is working.  To make it easier we'd assume the program is in a while and can check every so often to see if any keys have been pressed.  Let me know if you can help or if the question is unclear.

Sincerely,
RazvanL
Comment
Watch Question

Commented:
use kbhit()

#include <conio.h>

while (1) {
    if (kbhit()) {
        char c = getchar(); // Get the hit char
    }
}

Author

Commented:
Hi,

I do belive the program will halt waiting for getchar();

I need somethilng like

while(1)
{
  if(keypressed)
    dothis();
  ... keep doing this ...
}

In other words it would run that piece of code as long as no key is pressed.  Getchar() , at least last I used it, would stop and wait for a character to be entered.

Sincerely,
RazvanL.

Commented:
This is what I have show you.
Use kbhit()

keypressed  --> kbhit()

Author

Commented:
Hi,

Sorry I looked over the code quickly.  KBHIT() is a DOS system call so it doesn't work in Unix.  Conio.h is not a library file present in the Unix environment which I am using.  My life would probably be much easier if this thing was for DOS.

Sincerely,
RazvanL.

Author

Commented:
Hi,

Thanks for the link.  I had a long winded way of doing it, but I think I like this a lot more.  It actually looks quite interesting so I think I'll read up more on the whole Curses library.

Sincerely,
RazvanL.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.