如何使用C++移动鼠标

4

我希望通过C++脚本移动鼠标光标。 我正在使用Visual C ++ 2010 Express在Parallels内的Windows 7中创建控制台应用程序。

我知道SetCursorPos方法,但它根本不起作用(什么都不做)。

我成功地使用SendInput模拟了点击,但它实际上并没有移动鼠标。

这是我的代码:

#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));
}

3
你确定它没有被移动吗?也许虚拟机软件会立刻将它移回原位。(当然,虚拟机内的光标移动函数不会影响主机系统,因此主机鼠标指针仍然停留在虚拟机窗口上原来的位置)。 - Ben Voigt
展示你的代码。除非我们看到你已经尝试过什么,否则我们无法帮助你。 - selbie
你是如何尝试使用 SetCursorPos 的?至于 SendInput,你可能需要有三个事件:移动、按下按钮和松开按钮。 - chris
SetCursorPos 对我没用。至于 SendInput,所有这三个事件都在一个命令中完成(正如在网络上看到的示例一样)。 - jerkan
@BenVoigt “虚拟机内的光标移动函数当然不会影响主机系统” - 让我们不要混淆“不应该”和“不能”的概念...! :-/ - HostileFork says dont trust SE
2个回答

6
这是由于Parallels中的SmartMouse处于开启或自动模式。为了让Parallels虚拟机中的程序通过SetCursorPos控制鼠标,您需要先隐藏光标。您可以在进行任何鼠标移动(例如SetCursorPos)之前使用ShowCursor(0);来实现这一点。现在,即使SmartMouse设置为自动或关闭状态,您也将能够控制鼠标。

2
我找到了问题所在。原来 Parallels 有一个叫做 Smart Mouse 的功能,允许你在 OSX 和 Windows 之间自由移动鼠标。一旦我停用了它,鼠标就按照预期移动了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接