跳转到输入坐标定义的控制台屏幕位置

Jump to console screen position defined by entering coordinate

我有使用 Codeblocks c++ 创建的简单控制台应用程序 IDE。我想通过输入坐标将光标跳到任何屏幕位置。如何实现?

您可以使用 Windows Console API 中的函数。 为此,您只需要包含 windows.h header.

SetConsoleCursorPosition( HANDLE,COORD ) should do the trick.

查看 Microsoft 文档中的 documentation

这是一个演示示例:

#include<iostream>
#include<windows.h>
#include<cstdio>

using namespace std;

void changeCursor( int columnPos, int rowPos )
{
   HANDLE handle;      /// A HANDLE TO CONSOLE SCREEN BUFFER

   /// COORD STRUCTURE CONTAINS THE COLUMN AND ROW
   /// OF SCREEN BUFFER CHARACTER CELL
   COORD coord;

   coord.X = columnPos;
   coord.Y = rowPos;

   /// RETURNS A HANDLE TO THE SPECIFIED DEVICE.

   handle = GetStdHandle(STD_OUTPUT_HANDLE);   /// STD_OUTPUT_HANDLE MEANS STANDARD
                                            /// OUTPUT DEVICE(console screen buffer)

   SetConsoleCursorPosition( handle,coord );   /// SETS CURSOR POSITION IN SPECIFIED
                                            /// CONSOLE SCREEN BUFFER
}

int main()
{
   int xCoord,yCoord;
   cout<<"Lorem Ipsum is simply dummy text of \nthe printing and typesetting industry.\nLorem Ipsum has been the industry's standard \ndummy text ever since the 1500.";

   cout<<endl<<endl<<"Coordinates of Column and Row(zero indexed): ";

   cin>>xCoord>>yCoord;

   getchar();
   changeCursor(xCoord,yCoord);        /// YOUR FUNCTION TO SET NEW CURSOR

   getchar();          /// KEEP THE CONSOLE FROM TERMINATING

   return 0;
}

输出:

Lorem Ipsum is simply dummy text of
the printing and typesetting industry.
Lor*e*m Ipsum has been the industry's standard
dummy text ever since the 1500.

Coordinates of Column and Row(zero indexed): 3 2

注意这里的坐标需要从左上角位置开始测量,即控制台屏幕的 (0,0) 位置。

X、Y 值是字符位置,因为它们指向屏幕缓冲区字符单元格。

在此处查看 Sample Output 指定的光标位置。