determining the current position of the cursor

Is there any possible way to determine the current position of the cursor on the console output screen? I'm doing a text-based project, and this is a very critical issue!!!

EDIT: IF that's not clear enough, let me put it this way. How can I get the coordinates of the screen cursor?
Last edited on
Console position:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <windows.h> 
#include <stdio.h>

int main() 
{
	int y = 0;
	int x = 0;

	while(true)
	{
		DWORD cNumRead;															
		INPUT_RECORD irInBuf[128];												

		SetConsoleMode( GetStdHandle(STD_INPUT_HANDLE), ENABLE_MOUSE_INPUT );	
																		
		DWORD EventCount;

		GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &EventCount);

		while (EventCount > 0)
		{
			ReadConsoleInput( GetStdHandle(STD_INPUT_HANDLE), irInBuf, 128, &cNumRead );
			for (unsigned int i = 0; i < cNumRead; i++)
			{
				y = irInBuf[i].Event.MouseEvent.dwMousePosition.Y;
				x = irInBuf[i].Event.MouseEvent.dwMousePosition.X;
			}
			GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &EventCount);
		}

		printf("Y = %d  \nX = %d  \n", y, x);
		COORD pos = {0,0};
		SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
	}
	return 0; 
}
mythios's code gets the current mouse coordinates. Is that what you meant?

If not, then frankly, your project probably needs some design help. You should know where the cursor is. In any case, here is a simple function to get the cursor's position:

1
2
3
4
5
6
7
8
9
10
11
12
#include <windows.h>

bool wherexy( unsigned& x, unsigned& y )
  {
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  HANDLE                     out = GetStdHandle( STD_OUTPUT_HANDLE );
  if (!GetConsoleScreenBufferInfo( out, &csbi ))
    return false;
  x = csbi.dwCursorPosition.X;
  y = csbi.dwCursorPosition.Y;
  return true;
  }


Coordinates start at (0, 0) in the upper-left hand corner. If your console window is sized such that scrollbars appear, it is possible that the user has scrolled this location out of view.

[derail]
This can be done in *nix too... usually. (It depends on your terminfo and terminal/terminal emulator's actual capabilities.)

Hope this helps.
Topic archived. No new replies allowed.