c语言

c语言怎么获取鼠标当前位置

小亿
264
2023-08-10 15:40:35
栏目: 编程语言

在C语言中,要获取鼠标的当前位置,需要使用操作系统提供的相关函数。

在Windows操作系统中,可以使用GetCursorPos函数获取鼠标的当前坐标。该函数的原型为:

BOOL GetCursorPos(LPPOINT lpPoint);

其中,lpPoint是一个指向POINT结构的指针,用于存储鼠标的坐标。

下面是一个示例代码,演示如何使用GetCursorPos函数获取鼠标的当前位置:

#include <windows.h>
int main() {
POINT cursorPos;
if (GetCursorPos(&cursorPos)) {
printf("鼠标当前位置:(%d, %d)\n", cursorPos.x, cursorPos.y);
} else {
printf("获取鼠标位置失败\n");
}
return 0;
}

在Linux操作系统中,可以使用X11库提供的函数获取鼠标的当前位置。

下面是一个示例代码,演示如何使用X11库获取鼠标的当前位置:

#include <stdio.h>
#include <X11/Xlib.h>
int main() {
Display *display;
Window root;
XEvent event;
int x, y;
display = XOpenDisplay(NULL);
root = DefaultRootWindow(display);
XQueryPointer(display, root, &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
x = event.xbutton.x;
y = event.xbutton.y;
printf("鼠标当前位置:(%d, %d)\n", x, y);
XCloseDisplay(display);
return 0;
}

注意,Linux下使用X11库获取鼠标位置的代码需要连接X11库,可以使用以下命令进行编译:

gcc -o get_mouse_position get_mouse_position.c -lX11

上述代码仅演示了如何获取鼠标的当前位置,实际应用中可能需要结合其他代码进行处理。

0
看了该问题的人还看了