Get Mouse Position in C: Full Guide

In C language, in order to obtain the current position of the mouse, one typically needs to use relevant functions provided by a graphics library or the operating system. Taking Windows operating system as an example, below is a method to obtain the current position of the mouse:

  1. Firstly, the Windows.h header file needs to be included.
#include <Windows.h>
  1. Retrieve the current screen coordinates of the mouse cursor by using the GetCursorPos function.
POINT cursorPos;
GetCursorPos(&cursorPos);
  1. The coordinates obtained are saved in a POINT structure, and the x and y coordinates can be obtained by accessing the members of the structure.
int x = cursorPos.x;
int y = cursorPos.y;

The complete example code is as follows:

#include <Windows.h>

int main() {
    POINT cursorPos;
    GetCursorPos(&cursorPos);
    int x = cursorPos.x;
    int y = cursorPos.y;
    
    printf("当前鼠标位置:x = %d, y = %d\n", x, y);
    
    return 0;
}

It should be noted that the above sample code can only run on Windows operating systems. If running on other operating systems, you would need to use the corresponding functions provided by that operating system to obtain the mouse position.

bannerAds