.Net下的鼠标键盘模拟技术实战
3.基于驱动方式的鼠标键盘模拟
在C#中实现基于驱动的鼠标键盘模拟。现在的大多数鼠标和键盘都采用了USB接口,那么我们想更深层次的模拟鼠标和键盘的操作就需要对USB端口进行读写。那么最好的方法是自己写一个鼠标或键盘驱动,不过这种方案对于只是想模拟鼠标和键盘事件的开发者来说是不可取的,主要是因为没有经过充分测试的驱动会影响系统的稳定行,并且要开发一个完整的驱动是需要比较长的周期的。幸好,Microsoft还是为我们提供了几个操作USB接口的API函数,下面我来说明一下我们将在程序中用到的这几个API函数:
(1) 获取一个可用的GUID函数,因为每一个设备驱动都需要一个唯一标识那就是GUID。
[DllImport("hid.dll", SetLastError = true)]
protected static extern void HidD_GetHidGuid(out Guid gHid);
(2) 为设备的详细信息分配一个内存块函数
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags);
(3) 释放上一个函数分配的内存函数
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
(4) 从设备信息中获取设备的接口数据
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData);
(5) 从设备接口数据中获取接口的详细信息的函数
[DllImport("setupapi.dll", SetLastError = true)]
protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData);
(6) 为设备信息的删除和插入注册一个窗口
[DllImport("user32.dll", SetLastError = true)]
protected static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags);
(7) 释放上一个函数创建的窗口资源
[DllImport("user32.dll", SetLastError = true)]
protected static extern bool UnregisterDeviceNotification(IntPtr hHandle);
(8) 获取一个打开的设备的详细信息到内存
[DllImport("hid.dll", SetLastError = true)]
protected static extern bool HidD_GetPreparsedData(IntPtr hFile, out IntPtr lpData);
(9) 释放上一个函数所处理的内存
[DllImport("hid.dll", SetLastError = true)]
protected static extern bool HidD_FreePreparsedData(ref IntPtr pData);
(10) 从HidD_GetPreparsedData函数处理的内存中获取设备的可用信息
[DllImport("hid.dll", SetLastError = true)]
protected static extern int HidP_GetCaps(IntPtr lpData, out HidCaps oCaps);
(11) 创建我们要操作驱动的映射文件
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate);
(12) 关闭设备的文件句柄
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern int CloseHandle(IntPtr hFile);
0
相关文章