鍵盤管理
我們打造一個簡單的單屏編輯器
首先構造一個僅帶輸入功能的編輯器,使用wgetch來捕捉輸入。
#include
#include
#include
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
initscr();
clear();
noecho();
cbreak();
if(has_colors() == FALSE)
{
endwin();
printf("你的終端不支持色彩!\n");
return (1);
}
start_color(); /*啟動color 機制*/
init_pair(1, COLOR_GREEN, COLOR_BLACK);
WINDOW *win1;
int width=COLS-14;
int height=LINES-14;
int x,y;
win1=newwin(height,width,7,7);//新窗口(行,列,begin_y,begin_x)
keypad(win1,TRUE);
box(win1,ACS_VLINE,ACS_HLINE);
wattron(win1,COLOR_PAIR(1));
wrefresh(win1);
getyx(win1,y,x);
++y;++x;
while(1){
int c=mvwgetch(win1,y,x);
++x;
if (x>=width-1){
++y;
x=1;
}
if (y>=height-1){
y=1;
}
mvwprintw(win1,y,x,"%c",c);
wrefresh(win1);
}
wattroff(win1,COLOR_PAIR(1));
endwin();
return 0;
}
運行
dp@dp:~/cursestest % gcc -lncursesw a.c -o mytest
dp@dp:~/cursestest % ./mytest
vc/yvPy1xNans9ajrNLGtq+3vc/yvPyjrL/J0sa2r7niseqjrLKiseC8rbniseq0prXExNrI3aGjPC9wPgo8cD4jaW5jbHVkZSA8bG9jYWxlLmg+PC9wPgo8cD4jaW5jbHVkZSA8c3RkaW8uaD48L3A+CjxwPiNpbmNsdWRlIDxuY3Vyc2VzLmg+PC9wPgo8cD5pbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKTwvcD4KPHA+ezwvcD4KPHA+c2V0bG9jYWxlKExDX0FMTCw="");
initscr();
clear();
noecho();
cbreak();
if(has_colors() == FALSE)
{
endwin();
printf("你的終端不支持色彩!\n");
return (1);
}
start_color(); /*啟動color 機制*/
mvprintw(5,COLS/2-10,"簡單編輯器-僅限於單個屏幕的編輯");
refresh();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
WINDOW *win1;
int width=COLS-14;
int height=LINES-14;
int x,y;
win1=newwin(height,width,7,7);//新窗口(行,列,begin_y,begin_x)
keypad(win1,TRUE);
box(win1,ACS_VLINE,ACS_HLINE);
wattron(win1,COLOR_PAIR(1));
wrefresh(win1);
getyx(win1,y,x);
++y;++x;
while(1){
int c=mvwgetch(win1,y,x);
switch(c)
{
case KEY_RIGHT:
++x;
if (x>=width-1) {
++y;
x=1;
}
break;
case KEY_LEFT:
--x;
if (x<1){
--y;
x=width-2;
}
break;
case KEY_UP:
--y;
if (y<1){
y=height-2;
}
break;
case KEY_DOWN:
++y;
if (y>=height-1){
y=1;
}
break;
default:
mvwprintw(win1,y,x,"%c",c);
++x;
if (x>=width-1){
++y;
x=1;
}
if (y>=height-1){
y=1;
}
wrefresh(win1);
}
}
wattroff(win1,COLOR_PAIR(1));
endwin();
return 0;
}
dp@dp:~/cursestest % gcc -lncursesw a.c -o mytest
dp@dp:~/cursestest % ./mytest