1

我希望制作一个与游戏手柄一起使用的简单程序,并且可以从程序外部控制鼠标和关键字事件。我的目标是能够在沙发上控制电脑。

我当前的代码在Update()

protected override void Update(GameTime gameTime)
{
    //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
    //    Exit();

    var gamePadStates = Enum.GetValues(typeof (PlayerIndex)).OfType<PlayerIndex>().Select(GamePad.GetState);
    var mouseState = Mouse.GetState();

    var direction = Vector2.Zero;
    const int speed = 5;


    // Gamepad
    foreach (var input in gamePadStates.Where(x => x.IsConnected))
    {
        if (input.IsButtonDown(Buttons.DPadDown))
            direction.Y += 1;
        if (input.IsButtonDown(Buttons.DPadUp))
            direction.Y -= 1;
        if (input.IsButtonDown(Buttons.DPadLeft))
            direction.X -= 1;
        if (input.IsButtonDown(Buttons.DPadRight))
            direction.X += 1;

        direction.X += input.ThumbSticks.Left.X;
        direction.Y -= input.ThumbSticks.Left.Y;
    }


    var oldPos = new Vector2(mouseState.X, mouseState.Y);

    if (direction != Vector2.Zero)
    {
        var newPos = oldPos;
        direction *= speed;
        newPos += direction;
        //newPos.X = MathHelper.Clamp(newPos.X, 0, GraphicsDevice.DisplayMode.Width);
        //newPos.Y = MathHelper.Clamp(newPos.Y, 0, GraphicsDevice.DisplayMode.Height);
        Mouse.SetPosition((int)newPos.X, (int)newPos.Y);
        System.Diagnostics.Debug.WriteLine("New mouse pos = {0}, {1}", newPos.X, newPos.Y);
    }

    base.Update(gameTime);
}

编辑: 为了发送按键,我找到了这个

4

1 回答 1

3

在 XNA 中执行此操作与普通 C# 相同。要使用下面的代码,请确保您使用的是System.Runtime.InteropServices;命名空间。

免责声明:我认为这有点“肮脏”的代码,它用于user32.dll在 Windows 中调用点击,但它确实是唯一的方法。(改编自这里

首先,您需要 4 个常量来轻松使用不同类型的点击:

private const int MouseEvent_LeftDown = 0x02;
private const int MouseEvent_LeftUp = 0x04;
private const int MouseEvent_RightDown = 0x08;
private const int MouseEvent_RightUp = 0x10;

然后,您将需要挂钩鼠标事件:

[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void MouseEvent(uint dwFlags, uint dx, uint dy, uint cButtons,uint dwExtraInfo);

您现在可以编写方法来创建鼠标点击:

LeftClick(int x, int y)
{
     MouseEvent(MouseEvent_LeftDown | MouseEvent_LeftUp, x, y, 0, 0);
}

RightClick(int x, int y)
{
     MouseEvent(MouseEvent_RightDown | MouseEvent_RightUp, x, y, 0, 0);
}

...等等等等。您可以看到如何调整它以创建保持/拖动事件以模仿更多功能。

注意:我不确定这是否会在 中注册MouseState,但这不应该是必需的,因为您正在尝试使用它来控制计算机,并且游戏永远不需要使用鼠标状态。

于 2014-04-18T19:01:13.737 回答