如何使用c ++移动鼠标 [英] How to move mouse with c++

查看:234
本文介绍了如何使用c ++移动鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用c ++脚本移动鼠标光标。我在Parallels里面的Windows 7中使用Visual C ++ 2010 Express,我创建了一个控制台应用程序。

I want to move the mouse cursor with a c++ script. I am using Visual C++ 2010 Express in a Windows 7 inside Parallels and I created a console application.

我知道SetCursorPos方法,但它只是不工作。

I know SetCursorPos method but it is just not working (it does nothing).

我设法模拟使用SendInput的点击,但实际上并不移动鼠标。

I managed to simulate clicks with SendInput but it does not actually move the mouse.

代码:

#include <Windows.h>
#include <Tlhelp32.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <time.h>

void mouseLeftClick(const int x, const int y);

// window
HWND hWindow;

int main()
{
    // find window
    hWindow = FindWindow(NULL, "Calculadora");

    if (NULL == hWindow) {
        OutputDebugStringA("Couldn't find application.");
    }else{

        if (!SetForegroundWindow(hWindow)) {
            OutputDebugStringA("Couldn't set application to foreground.");
        }else{
            // click on 1
            mouseLeftClick(20 265));
            Sleep(500);
            // click on 2
            mouseLeftClick(60, 265);
            Sleep(500);
        }
    }
    return 0;
}

void mouseLeftClick(const int x, const int y)
{ 
    // get the window position
    RECT rect;
    GetWindowRect(hWindow, &rect);

    // calculate scale factor
    const double XSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CXSCREEN) - 1);
    const double YSCALEFACTOR = 65535 / (GetSystemMetrics(SM_CYSCREEN) - 1);

    // get current position
    POINT cursorPos;
    GetCursorPos(&cursorPos);
    double cx = cursorPos.x * XSCALEFACTOR;
    double cy = cursorPos.y * YSCALEFACTOR;

    // calculate target position relative to application
    double nx = (x + rect.left) * XSCALEFACTOR;
    double ny = (y + rect.top) * YSCALEFACTOR;

    INPUT Input={0};
    Input.type = INPUT_MOUSE;

    Input.mi.dx = (LONG)nx;
    Input.mi.dy = (LONG)ny;

    // set move cursor directly and left click
    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;

    SendInput(1,&Input,sizeof(INPUT));
}


推荐答案

智能鼠标为开或自动。
为了让Parallels VM中的程序使用 SetCursorPos 来控制鼠标,您需要先隐藏光标。你可以使用 ShowCursor(0); 来做任何鼠标移动。 SetCursorPos
现在,您将能够控制鼠标,而SmartMouse设置为自动或关闭。

This happens in Parallels because of SmartMouse is On or on Auto. In order for a program in Parallels VM to control the mouse with SetCursorPos you need to hide cursor first. You can do that with ShowCursor(0); before you do any mouse movement e.g. SetCursorPos. Now you will be able to control the mouse while SmartMouse is set to Auto or Off.

这篇关于如何使用c ++移动鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆