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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <limits.h>
#include <iostream>
using namespace std;
void gotoxy(int x, int y)
{
COORD coord;
coord.X = (SHORT)x;
coord.Y = (SHORT)y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
// Get screen frame rate, as there's no point going any faster
DWORD frameRate = 0;
DEVMODEA devMode = {0};
devMode.dmSize = sizeof(DEVMODE);
if(EnumDisplaySettingsA(NULL, ENUM_CURRENT_SETTINGS, &devMode))
frameRate = devMode.dmDisplayFrequency;
else
frameRate = 60; // default value if fail to get actual value
// get our window
HWND hWnd = GetConsoleWindow();
// to remember where we were last time
POINT posLast = {LONG_MIN, LONG_MIN};
while(1)
{
// get current mouse position in screen coords
POINT pos = {0, 0};
if (GetCursorPos(&pos))
{
// convert position to client window coords
if (ScreenToClient(hWnd, &pos))
{
// get window's client rect
RECT rcClient = {0};
GetClientRect(hWnd, &rcClient);
// if mouse cursor is inside rect
if (PtInRect(&rcClient, pos))
{
// and if we've moved since last time
if ((posLast.x != pos.x) || (posLast.y != pos.y))
{
// get size and position of console window/buffer in rows and columns
CONSOLE_SCREEN_BUFFER_INFO info = {0};
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
const SMALL_RECT& smRect = info.srWindow;
// calculate row and column corresponding to mouse position
// (note this takes accounts of console buffer scrolling)
int x = smRect.Left + (pos.x * (smRect.Right - smRect.Left))
/ (rcClient.right - rcClient.left);
int y = smRect.Top + (pos.y * (smRect.Bottom - smRect.Top ))
/ (rcClient.bottom - rcClient.top );
// move to new position and output 'o'
gotoxy(x, y);
cout << 'o';
// update title bar
char title[64] = "";
wsprintfA(title, "Mouse Test - (%d, %d)", x, y);
SetConsoleTitleA(title);
// and last position
posLast = pos;
}
}
else
{
// update title bar (for testing purposes) to know we don't care
// where the mouse is at the moment
SetConsoleTitleA("Mouse Test - (out of window)");
}
// wait a short while
Sleep(1000 / frameRate);
}
}
}
return 0;
}
|