-2

If I have a two dimensional array in the console, for example:

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

I want to click the array with my mouse and get indexes of the array. For example I click position (3;3) and it outputs in the console "x = 3 and y = 3"

How can I do that in C++? (I'm using Windows)

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
katinas
  • 432
  • 6
  • 11
  • 4
    Take a look at https://stackoverflow.com/questions/6285270/how-can-i-get-the-mouse-position-in-a-console-program to understand how to get mouse position in a console window. Then converting that position to a position on you array is just maths which only you know how to do as only you know where you printed that array – Mike Vine Oct 12 '18 at 11:00

1 Answers1

2

Try this code:

#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;
                }
            }
}

This should output the coordinates of the mouse click location.

execut4ble
  • 138
  • 8