我要求光標位置。如果我在100ms後沒有回答(這是任意的),我想控制檯不是ansi。
/* This function tries to get the position of the cursor on the terminal.
It can also be used to detect if the terminal is ANSI.
Return 1 in case of success, 0 otherwise.*/
int console_try_to_get_cursor_position(int* x, int *y)
{
fd_set readset;
int success = 0;
struct timeval time;
struct termios term, initial_term;
/*We store the actual properties of the input console and set it as:
no buffered (~ICANON): avoid blocking
no echoing (~ECHO): do not display the result on the console*/
tcgetattr(STDIN_FILENO, &initial_term);
term = initial_term;
term.c_lflag &=~ICANON;
term.c_lflag &=~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &term);
//We request position
print_escape_command("6n");
fflush(stdout);
//We wait 100ms for a terminal answer
FD_ZERO(&readset);
FD_SET(STDIN_FILENO, &readset);
time.tv_sec = 0;
time.tv_usec = 100000;
//If it success we try to read the cursor value
if (select(STDIN_FILENO + 1, &readset, NULL, NULL, &time) == 1)
if (scanf("\033[%d;%dR", x, y) == 2) success = 1;
//We set back the properties of the terminal
tcsetattr(STDIN_FILENO, TCSADRAIN, &initial_term);
return success;
}
難道沒有辦法讓ANSI命令不把'^ [[x; yR'寫到終端上嗎?我想默默地檢索座標,而不會在終端屏幕上發生任何可見的變化。但是這寫入到終端(創建文本GUI時不合需要),從而改變了光標的座標(這使得它絕對無用)。 – Witiko
這就是爲什麼curses(和ncurses)存在,所以你不必擔心所有這些細節。 – Craig
當然,但ncurses完全是英國媒體報道。這就是爲什麼我編寫自己的輕量級ANSI轉義序列庫,它僅支持VT100。但是,是的,好像我只需要使用ncurses並嘗試對其進行反向工程即可找到解決此問題的方法。 – Witiko