在VS Code中使用C语言实现鼠标检测的可行方法求助
检测鼠标连接的C语言实现(替代DOS中断方法)
你之前使用的dos.h、int86调用是16位DOS系统时代的老方法,现代Windows环境(包括MinGW)已经不再支持这类接口,因此需要改用原生的Win32 API或跨平台库来实现鼠标检测。
方案一:Win32 API(Windows平台原生支持)
Windows提供了GetSystemMetrics函数可以快速判断系统是否存在鼠标,MinGW完全支持该API,无需额外依赖。
代码示例
#include <stdio.h> #include <windows.h> int main() { // SM_MOUSEPRESENT 返回非零值表示系统检测到至少一个鼠标 if (GetSystemMetrics(SM_MOUSEPRESENT)) { printf("鼠标已连接\n"); } else { printf("未检测到鼠标\n"); } return 0; }
编译说明
MinGW编译时需要链接user32系统库,命令如下:
gcc -o mouse_detect mouse_detect.c -luser32
如果需要获取更详细的鼠标设备信息(比如多个鼠标的数量),可以使用GetRawInputDeviceList函数:
#include <stdio.h> #include <windows.h> #include <stdlib.h> int main() { UINT device_count = 0; // 先获取输入设备总数 if (GetRawInputDeviceList(NULL, &device_count, sizeof(RAWINPUTDEVICELIST)) == -1) { printf("获取设备列表失败\n"); return 1; } // 分配内存存储设备列表 RAWINPUTDEVICELIST* devices = malloc(device_count * sizeof(RAWINPUTDEVICELIST)); if (!devices) { printf("内存分配失败\n"); return 1; } if (GetRawInputDeviceList(devices, &device_count, sizeof(RAWINPUTDEVICELIST)) == -1) { printf("获取设备列表失败\n"); free(devices); return 1; } // 统计鼠标设备数量 int mouse_count = 0; for (UINT i = 0; i < device_count; i++) { if (devices[i].dwType == RIM_TYPEMOUSE) { mouse_count++; } } if (mouse_count > 0) { printf("检测到 %d 个鼠标设备\n", mouse_count); } else { printf("未检测到鼠标设备\n"); } free(devices); return 0; }
方案二:跨平台实现(SDL2库)
如果你的程序需要在Windows、Linux、macOS等多平台运行,可以使用SDL2库,它提供了统一的输入设备检测接口。
代码示例
#include <stdio.h> #include <SDL2/SDL.h> int main() { // 初始化SDL视频子系统(输入设备检测依赖此模块) if (SDL_Init(SDL_INIT_VIDEO) != 0) { printf("SDL初始化失败: %s\n", SDL_GetError()); return 1; } int has_mouse = 0; // 枚举所有输入设备,查找鼠标类型 int device_count = SDL_GetNumInputDevices(); for (int i = 0; i < device_count; i++) { SDL_InputDeviceID dev_id = SDL_GetInputDevice(i); if (SDL_GetInputDeviceType(dev_id) == SDL_INPUT_DEVICE_MOUSE) { has_mouse = 1; break; } } if (has_mouse) { printf("检测到鼠标\n"); } else { printf("未检测到鼠标\n"); } SDL_Quit(); return 0; }
编译说明
需要先安装SDL2库,MinGW环境下编译命令如下:
gcc -o mouse_detect mouse_detect.c -lSDL2
内容的提问来源于stack exchange,提问作者JY Chang
相关产品推荐
相关产品推荐

