Mouse Cursor Windows

Hello Forum People.....

The following program is not working as intended.

I want to mark 'o' at the cursor position in window.
The screen to client part doesn't seem to work.

please help, its an integral part of a bigger program, any help would be greatly appreciated.........

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
37
38
39
40
41
42
43
#include <iostream>
#include<windows.h>

using namespace std;

void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main()
{
cout << "Hello world!" << endl;

int x,y;
while(1)
{

POINT p;
HWND hWnd;
if (GetCursorPos(&p))
{

}

if (ScreenToClient(hWnd,&p))
{

}

gotoxy(p.x,p.y);
cout<<'o';
Sleep(10);

}

return 0;
}

GetCursorPos will give you the position in pixels.
Your gotoxy function takes a position in characters.

Therefore in order for this to work, you'll have to convert your pixel coord to a character coord. To do this... you'll need to know how many pixels each character occupies.


This is slightly tricky, as the size of a character may vary on user settings (ie: what font they decide to use for the console, and what size the font is).

One way to do it would be to get the rows/cols of the window with GetConsoleScreenBufferInfo:

1
2
3
4
5
CONSOLE_SCREEN_BUFFER_INFO info;

GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
int cols = info.srWindow.Right - info.srWindow.Left + 1;
int rows = info.srWindow.Bottom - info.srWindow.Top + 1;


Then get the pixel size of the window with GetClientRect.

pixelwidth / cols = pixel_width_of_each_character.

So to convert a mouse pixel coord to a console character coord:

1
2
3
4
int x = mouse_x * cols / windowpixelwidth;
int y = mouse_y * rows / windowpixelheight;

gotoxy( x, y );




But note for GetClientRect() and ScreenToClient() to work, you have to obtain the HWND to the console window. In your code you are just giving it an uninitialized HWND so that won't work.

Getting the HWND to the console does not appear to be a simple task. Here is an MSDN article I found on it:
http://support.microsoft.com/kb/124103





Anyway... long story short.... this is one of the things the console is not really well designed to do. You might be better off leaving the console and using a graphic lib. Something like this would be significantly easier with SFML or SDL.
Topic archived. No new replies allowed.