手动调用鼠标单击XNA
本文关键字:单击 XNA 鼠标 调用 | 更新日期: 2023-09-27 17:58:56
我想制作一个简单的程序,用于游戏板,可以从程序外部控制鼠标和关键字事件。我的目标是能够在沙发上控制电脑。
我在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);
}
编辑:对于发送按键,我发现了这个库
在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
中注册,但这不应该是必要的,因为你正试图使用它来控制计算机,游戏永远不应该使用鼠标状态。