Unity捕获外部的鼠标与键盘事件
- 项目背景
winform与unity在实现通信的过程中,需要unity监听winform操作的时候的鼠标按下与键盘按下功能
- 解决思路
使用通过C#代码,接入windows的事件系统,完成相应逻辑处理
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
//移除钩子
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
实现步骤:
1.设置钩子函数
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
2.加入钩子的回调函数
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_LBUTTONUP)
{
int vkCode = Marshal.ReadInt32(lParam);
//Debug.Log("ASCII:" + vkCode);
//Debug.Log(Input.mousePosition);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
3.demo链接