c# DX游戏鼠标点击指定坐标 后台鼠标
时间: 2023-11-16 20:06:13 浏览: 222
在C#中,可以使用User32.dll库中的鼠标事件函数来模拟鼠标点击。
以下是示例代码:
```csharp
using System;
using System.Runtime.InteropServices;
public class MouseSimulator
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public uint type;
public InputUnion U;
public static int Size
{
get { return Marshal.SizeOf(typeof(INPUT)); }
}
}
[StructLayout(LayoutKind.Explicit)]
struct InputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
public int dx;
public int dy;
public uint mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
const uint MOUSEEVENTF_ABSOLUTE = 0x8000;
const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
const uint MOUSEEVENTF_LEFTUP = 0x0004;
const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
const uint MOUSEEVENTF_MOVE = 0x0001;
const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
const uint MOUSEEVENTF_RIGHTUP = 0x0010;
public static void Click(int x, int y)
{
var inputList = new INPUT[2];
// Move to the specified coordinates
inputList[0].type = inputList[1].type = 0;
inputList[0].U.mi.dx = inputList[1].U.mi.dx = (int)(x * (65535.0f / Screen.PrimaryScreen.Bounds.Width));
inputList[0].U.mi.dy = inputList[1].U.mi.dy = (int)(y * (65535.0f / Screen.PrimaryScreen.Bounds.Height));
inputList[0].U.mi.mouseData = inputList[1].U.mi.mouseData = 0;
inputList[0].U.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
inputList[1].U.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN;
SendInput(2, inputList, INPUT.Size);
inputList[0].U.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP;
inputList[1].U.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
SendInput(2, inputList, INPUT.Size);
}
}
```
这里的Click方法使用了SendInput函数模拟鼠标移动和点击事件。你可以在需要模拟鼠标点击的地方调用该方法,并传入需要点击的坐标值。例如:
```csharp
MouseSimulator.Click(100, 100); // 模拟点击(100, 100)的位置
```
阅读全文