【问题标题】:Jump to console screen position defined by entering coordinate跳转到输入坐标定义的控制台屏幕位置
【发布时间】:2019-12-10 16:20:15
【问题描述】:

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

【问题讨论】:

  • 我建议使用像 ncurses 这样的库。

标签: c++ codeblocks


【解决方案1】:

您可以使用来自Windows Console API 的函数。 为此,您只需要包含 windows.h 标头即可。

SetConsoleCursorPosition( HANDLE,COORD ) 应该可以解决问题。

查看 Microsoft Docs 中的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多