首 页文章中心

Linux学习网

您的位置Linux学习网 > Linux程序开发 > 文章内容

linux c语言实现getch()

作者:佚名  来源:不详  发布时间:2007-7-5 8:14:00

linux c语言实现getch()

以下是网络资料,还没经过测试



#include

#include



static struct termio ttysave;

void restore(void);

char getch(void);

int main(void)

{.....}



char getch(void)

{

static char ch;

static int total,flag=1;

struct termio tty;

if (flag)

{

flag=0;

if(ioctl(0,TCGETA,&tty)==-1)

{

perror("ioctl");

exit(1);

}

ttysave=tty;

tty.c_lflag &=~(ICANON|ECHO|ISIG);

tty.c_cc[VMIN]=1;

tty.c_cc[VTIME]=0;

if(ioctl(0,TCSETAF,&tty)==-1)

{

..

perror("ioctl");

exit(2);

}

}

switch(total=read(0,&ch,1))

{

case -1:

..;

exit(3);

case 0:

fputs("EOF error!",stderr);

exit(4);

default:

;

}

...

return(ch);

}







第二种:

  可以检测 PageUP PageDown以及Arrows等按键,F1, F2等功能键,
会被解释成输入一个字符序列。功能的实现是通过ioctl调整终端的属性。



#include
#include
#include

int getch( );

int main( )
{
char ch;
while(1){
ch = getch( );
printf("You Pressed %c\n", ch);
if(ch == 'E')
break;
}
}

int getch()
{
char ch;
struct termios save, ne;
ioctl(0, TCGETS, &save);
ioctl(0, TCGETS, &ne);
ne.c_lflag &= ~(ECHO | ICANON);
ioctl(0, TCSETS, &ne);
read(0, &ch, 1);
ioctl(0, TCSETS, &save);
return ch;
}

收藏本页到: 365Key | del.icio.us | | 添加到雅虎收藏+
  • 网站帮助 - 广告合作 - 网站地图