Output characters anywhere on the screen

Because the Windo cursor positioning needs to use the SetConsoleCursorPositionfunctions in the windows.h header file , its usage is:

SetConsoleCursorPosition(HANDLE hConsoleOutput, COORD  dwCursorPosition);

hConsoleOutputRepresents the console buffer handle, which can be obtained through GetStdHandle(STD_OUTPUT_HANDLE); dwCursorPositionis the cursor position, that is, which row and column, it is a structure of type COORD. The function of ws operating system, so the code in this section cannot run under Linux and Mac OS.

For example, position the cursor on the third row and third column of the console:

//定义光标位置
COORD coord;
coord.X = 3;  //第3行
coord.Y = 3;  //第3列
//获取控制台缓冲区句柄,固定写法
HANDLE ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
//设置光标位置,固定写法
SetConsoleCursorPosition(ConsoleHandle, coord);
#include <stdio.h>
#include <windows.h>

int main(){
    //定义光标位置
    COORD coord;
    coord.X = 3;  //第3行
    coord.Y = 3;  //第3列
    //获取控制台缓冲区句柄
    HANDLE ConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    //设置光标位置
    SetConsoleCursorPosition(ConsoleHandle, coord);
   
    printf("http://c.biancheng.net\n");

    return 0;
}

operation result:

Note: The upper left corner of the window is row 0 and column 0, not row 1 and column 1 as we usually think. Many counts in programming languages ​​start from 0 instead of 1.

#include <stdio.h>
#include <windows.h>

//设置光标位置
void setCursorPosition(int x, int y);
//设置文字颜色
void setColor(int color);

int main(){
    setColor(3);
    setCursorPosition(3, 3);
    puts("★");

    setColor(0XC);
    setCursorPosition(1, 1);
    puts("◆");

    setColor(6);
    setCursorPosition(6, 6);
    puts("■");

    return 0;
}

//自定义的光标定位函数
void setCursorPosition(int x, int y){
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//自定义的文字颜色函数
void setColor(int color){
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color) ;
}

Guess you like

Origin blog.csdn.net/qq_43629083/article/details/112982339