DirectX 鼠标模拟:使用 DirectInput 编写鼠标模拟代码
下面是使用 DirectX 模拟鼠标的代码示例:
#include <windows.h>
#include <dinput.h>
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
LPDIRECTINPUT8 g_pDI = NULL;
LPDIRECTINPUTDEVICE8 g_pMouse = NULL;
bool InitializeMouse(HWND hWnd)
{
// 创建 DirectInput 对象
if (FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDI, NULL)))
return false;
// 创建鼠标设备
if (FAILED(g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL)))
return false;
// 设置数据格式为鼠标
if (FAILED(g_pMouse->SetDataFormat(&c_dfDIMouse)))
return false;
// 设置协作级别
if (FAILED(g_pMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
return false;
// 启用鼠标设备
if (FAILED(g_pMouse->Acquire()))
return false;
return true;
}
void ReleaseMouse()
{
if (g_pMouse)
{
g_pMouse->Unacquire();
g_pMouse->Release();
g_pMouse = NULL;
}
if (g_pDI)
{
g_pDI->Release();
g_pDI = NULL;
}
}
void UpdateMouseState()
{
if (!g_pMouse)
return;
DIMOUSESTATE mouseState;
if (FAILED(g_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState)))
{
// 如果获取鼠标状态失败,尝试重新获取
g_pMouse->Acquire();
g_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState);
}
// 检查鼠标状态
if (mouseState.rgbButtons[0] & 0x80)
{
// 左键按下
}
// 鼠标坐标
int mouseX = mouseState.lX;
int mouseY = mouseState.lY;
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
// 初始化鼠标
if (!InitializeMouse(hWnd))
{
MessageBox(hWnd, "Failed to initialize mouse!", "Error", MB_OK | MB_ICONERROR);
PostQuitMessage(0);
}
break;
case WM_DESTROY:
// 释放鼠标
ReleaseMouse();
PostQuitMessage(0);
return 0;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 创建窗口
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WindowProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, "Mouse Simulation", NULL };
RegisterClassEx(&wc);
HWND hWnd = CreateWindow(wc.lpszClassName, "Mouse Simulation", WS_OVERLAPPEDWINDOW, 100, 100, 800, 600, GetDesktopWindow(), NULL, wc.hInstance, NULL);
// 显示窗口
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
MSG msg;
ZeroMemory(&msg, sizeof(msg));
// 消息循环
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// 更新鼠标状态
UpdateMouseState();
}
}
return 0;
}
这段代码创建了一个窗口,使用 DirectInput 模拟鼠标输入。它通过 InitializeMouse 函数来初始化鼠标设备,并通过 UpdateMouseState 函数来获取鼠标状态。在 WindowProc 函数中,可以处理窗口消息,如 WM_CREATE 和 WM_DESTROY 等。在 WinMain 函数中,创建了窗口并进入消息循环,通过调用 UpdateMouseState 函数来更新鼠标状态。
注意:为了编译通过,请确保已将 DirectX SDK 添加到项目的包含目录和链接器附加依赖项中,并将 DirectX 相关的库文件正确引入。
原文地址: https://www.cveoy.top/t/topic/o7bJ 著作权归作者所有。请勿转载和采集!