C语言编程——控制台程序光标控制

来源:互联网 发布:breed改mac 编辑:程序博客网 时间:2024/05/01 17:06

 

    对于C语言的初学者,基本上只能写一些控制台程序。然而有时候会涉及一些对光标的简单操作,现在一般都是用的VC++6.0,不再支持以前TC中的wherexwhereygotoxy等函数了,那么在VC中该怎样做呢?接下来,我就简单讲讲如何在VC中实现以上三个函数。

【以下x、y分别代表列数和行数】

//获取光标的位置xint wherex(){    CONSOLE_SCREEN_BUFFER_INFO pBuffer;    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);    return (pBuffer.dwCursorPosition.X+1);}

 

//获取光标的位置yint wherey(){    CONSOLE_SCREEN_BUFFER_INFO pBuffer;    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);    return (pBuffer.dwCursorPosition.Y+1);}
//设置光标的位置void gotoxy(int x,int y) {    COORD c;    c.X=x-1;    c.Y=y-1;    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);} 


 

###注意:在用这些函数的时候要引用头文件#includ<windows.h>###

下面来看一个具体应用的例子:

#include<stdio.h>#include<windows.h>int wherex(){    CONSOLE_SCREEN_BUFFER_INFO pBuffer;    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);    return (pBuffer.dwCursorPosition.X+1);}//获取光标的位置yint wherey(){    CONSOLE_SCREEN_BUFFER_INFO pBuffer;    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);    return (pBuffer.dwCursorPosition.Y+1);}//设置光标的位置void gotoxy(int x,int y) {    COORD c;    c.X=x-1;    c.Y=y-1;    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);} int main(){    int x, y;    int select;    gotoxy(10,5);    printf(" 学生C语言成绩管理系统");    gotoxy(15,8);    printf("*********************主菜单*********************");    gotoxy(15,9);    printf("* 1 输入 2 删除 *");    gotoxy(15,10);    printf("* 3 查找 4 修改 *");    gotoxy(15,11);    printf("* 5 插入 6 统计 *");    gotoxy(15,12);    printf("* 7 排序 8 保存 *");    gotoxy(15,13);    printf("* 9 显示 0 退出 *");    gotoxy(15,14);    printf("************************************************");    gotoxy(15,15);    printf("请输入你的选择(0-9):[ ]");    x=wherex();    y=wherey();    gotoxy(x-2,y);    scanf("%d",&select);    return 0;}