首页 > 解决方案 > 通过鼠标单击获取二维数组的索引

问题描述

如果我在控制台中有一个二维数组,例如:

  0123
0 OOOO
1 OOOO
2 OOOO
3 OOOX <--- mouse click here

我想用鼠标单击数组并获取数组的索引。例如,我单击位置 (3;3) 并在控制台中输出“x = 3 and y = 3”

我怎样才能在 C++ 中做到这一点?(我使用的是 Windows)

标签: c++arrayswindows

解决方案


试试这个代码:

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

int main()
{
    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
    INPUT_RECORD InputRecord;
    DWORD Events;
    COORD coord;
    SetConsoleMode(hin, ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT);
        while (1) {
                ReadConsoleInput(hin, &InputRecord, 1, &Events);
                switch (InputRecord.EventType) {
                case MOUSE_EVENT: // mouse input 

                    if (InputRecord.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)    //if mouse-1 is clicked
                    {
                        int x = InputRecord.Event.MouseEvent.dwMousePosition.X;    //mouse coordinates
                        int y = InputRecord.Event.MouseEvent.dwMousePosition.Y;
                        coord.X = x;
                        coord.Y = y;
                        SetConsoleCursorPosition(hout, coord);    //sets vursors position for output
                        std::cout <<"x = " << x << " y = "<<  y;
                    }
                    break;
                }
            }
}

这应该输出鼠标点击位置的坐标。


推荐阅读