C++实现鼠标点击和获取鼠标位置(编译环境visual studio 2022)

1环境说明

2获取鼠标位置的接口

cpp 复制代码
void GetMouseCurPoint()
{
    POINT mypoint;

    for (int i = 0; i < 100; i++)
    {
        GetCursorPos(&mypoint);//获取鼠标当前所在位置
        printf("% ld, % ld \n", mypoint.x, mypoint.y);
        Sleep(1000);
    }
}

3操作鼠标左键和右键的接口

cpp 复制代码
void MouseLeftDown()//鼠标左键按下 
{
    INPUT  Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
    SendInput(1, &Input, sizeof(INPUT));
}

void MouseLeftUp()//鼠标左键放开 
{
    INPUT  Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
    SendInput(1, &Input, sizeof(INPUT));
}

void MouseRightDown()//鼠标右键按下 
{
    INPUT  Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
    SendInput(1, &Input, sizeof(INPUT));
}

void MouseRightUp()//鼠标右键放开 
{
    INPUT  Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
    SendInput(1, &Input, sizeof(INPUT));
}

4鼠标移动的接口

cpp 复制代码
void MouseMove(int x, int y)//鼠标移动到指定位置 
{
    double fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN) - 1;//获取屏幕分辨率宽度 
    double fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN) - 1;//获取屏幕分辨率高度 
    double fx = x * (65535.0f / fScreenWidth);
    double fy = y * (65535.0f / fScreenHeight);

    printf("fScreenWidth %lf , fScreenHeight %lf, fx %lf, fy %lf \n", fScreenWidth, fScreenHeight, fx, fy);

    INPUT  Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
    Input.mi.dx = fx;
    Input.mi.dy = fy;
    SendInput(1, &Input, sizeof(INPUT));
}

5Main函数和头文件

cpp 复制代码
#include <stdint.h>
#include <Windows.h>
#include <stdio.h>

int main()
{
    Sleep(1000);          //延时函数

    GetMouseCurPoint();   //获取鼠标当前所在位置

    MouseMove(x, y);      //x, y坐标从GetMouseCurPoint()的打印中获取

    Sleep(10);            //move之后需要延时

    MouseLeftDown();

    Sleep(1);

    MouseLeftUp();

    Sleep(100);

    return 0;
}

6参考资料和说明

  • 参考链接

http://t.csdnimg.cn/ezeafhttp://t.csdnimg.cn/ezeaf

  • 代码下载链接

https://download.csdn.net/download/u013232419/88808663https://download.csdn.net/download/u013232419/88808663

  • 说明

代码部分已经全部放到正文中了,上述的资料需要下载积分1分(就当懒得复制的分吧,不是很喜欢动不动一个资料需要40多分,期望更多类似的分享)。

相关推荐
乙己40716 小时前
设计模式——单例模式(singleton)
java·c++·单例模式·设计模式
嵌入式小李.man17 小时前
linux中多路复用IO:select、poll和epoll
linux·c++
郝学胜-神的一滴17 小时前
QAxios研发笔记(二):在Qt环境下基于Promise风格简化Http的Post请求
开发语言·c++·笔记·qt·网络协议·程序人生·http
晨非辰17 小时前
《数据结构风云》:二叉树遍历的底层思维>递归与迭代的双重视角
数据结构·c++·人工智能·算法·链表·面试
Yupureki19 小时前
从零开始的C++学习生活 17:异常和智能指针
c语言·数据结构·c++·学习·visual studio
deng-c-f1 天前
配置(4):VScode c/c++编译环境的配置:c_cpp_properties.json
c语言·c++·vscode
应用市场1 天前
Godot C++开发指南:正确获取节点的Forward/Up/Right方向向量
c++·游戏引擎·godot
小-黯1 天前
OpenGL使用C++ 绘制三角形
c++·opengl·xmake
code_ing-1 天前
【Linux】命令行参数与环境变量
linux·c++·windows·笔记
wangjialelele1 天前
Qt中的常用组件:QWidget篇
开发语言·前端·c++·qt