简体   繁体   English

C#模拟鼠标移动不会影响前台应用程序

[英]C# Simulate mouse movement does not affect foreground application

I have two machines: A and B 我有两台机器:A和B

On A, I get the current (local) mouse position (x & y) and send send that mouse position over my local network to machine B. Machine B takes the incoming position X and Y and simulate the mouse movement using the example found here . 在A上,我获得当前(本地)鼠标位置(x&y)并将该鼠标位置通过我的本地网络发送到机器B。机器B使用传入的位置X和Y并使用此处找到的示例模拟鼠标的移动。 It all works fine and dandy - I can see the mouse moving, but for some reason, it does not affect the Window in the foreground on machine B. 一切正常而且很好-我可以看到鼠标在移动,但是由于某些原因,它不会影响机器B上前景中的窗口。

What is this "Window"? 这是什么“窗口”? It is a Unity3D application - a game. 它是一个Unity3D应用程序-一个游戏。 I expect that the mouse movement would cause the in-game camera to move around. 我希望鼠标移动会导致游戏中的摄像头移动。 Interestingly, if I do as described and then stop moving the mouse on machine A... and then move the mouse via the touchpad (or regular mouse) on machine B, it moves the in-game camera, as expected! 有趣的是,如果我按照说明进行操作,然后停止在机器A上移动鼠标,然后通过机器B上的触摸板(或常规鼠标)移动鼠标,则它会按预期移动游戏中的相机!

What is going on? 到底是怎么回事?

It seems that, for whatever reason, the code taken from here 看来,无论出于何种原因,从这里获取的代码

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

does not work...properly! 不能正常工作! My mouse would move, as expected, on the remote machine but the application that I was bringing to the foreground was not detecting the mouse movements. 我的鼠标将按预期在远程计算机上移动,但是我带到前台的应用程序未检测到鼠标的移动。

However, I did manage to get this to work using mouse_event : 但是,我确实设法使用mouse_event起作用:

[Flags]
public enum MouseEventFlags
{
    LeftDown = 0x00000002,
    LeftUp = 0x00000004,
    MiddleDown = 0x00000020,
    MiddleUp = 0x00000040,
    Move = 0x00000001,
    Absolute = 0x00008000,
    RightDown = 0x00000008,
    RightUp = 0x00000010
}

[DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

public static void MouseEvent(MouseEventFlags value, Point position)
{
    MousePoint position = position;

    mouse_event
        ((int)value,
         position.X,
         position.Y,
         0,
         0)
        ;
}

[StructLayout(LayoutKind.Sequential)]
public struct MousePoint
{
    public int X;
    public int Y;

    public MousePoint(int x, int y)
    {
        X = x;
        Y = y;
    }

}

To use it, just call: 要使用它,只需调用:

mouse_event(MouseEventFlags.Move,new MousePoint{X = YOUR_X, Y = YOUR_Y});

All credit goes to this SO answer . 所有的功劳都归功于这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM