三、 DirectInput
DirectInput是DirectX中的输入设备控件对象,它包括了对键盘、鼠标以及游戏杆的支持,使用DirectX的DirectInputCreate方法可以建立DirectInput对象,当建立一个DirectInput对象后,利用DirectInput对象的CreateDevice方法可以建立一个DirectInputDevice对象,使用DirectInputDevice对象可以获得对输入设备(键盘、鼠标、游戏杆)的控制。
下面通过一个简单的程序来了解DirectInput是如何工作的。首先建立一个新工程,加入Directx7说明库,在Form1中加入一个Timer控件和一个Label控件。然后在Form1中加入以下代码:
Option Explicit
Dim dx As New DirectX7 Dim di As DirectInput Dim diDEV As DirectInputDevice Dim diMouse As DirectInputDevice
Dim diState As DIKEYBOARDSTATE Dim diSMouse As DIMOUSESTATE
Dim iKeyCounter As Integer Dim ix, iy, iz
Private Sub Form_Load() Set di = dx.DirectInputCreate() If Err.Number <> 0 Then MsgBox "Direct Input设置错误,请确认再你的系统中是否安装了DirectX", _ vbApplicationModal End End If '建立一个键盘DirectInput对象 Set diDEV = di.CreateDevice("GUID_SysKeyboard") Set diMouse = di.CreateDevice("GUID_SysMouse")
diDEV.SetCommonDataFormat DIFORMAT_KEYBOARD diDEV.SetCooperativeLevel Me.hWnd, DISCL_BACKGROUND Or DISCL_NONEXCLUSIVE
diMouse.SetCommonDataFormat DIFORMAT_MOUSE diMouse.SetCooperativeLevel Me.hWnd, DISCL_BACKGROUND Or DISCL_NONEXCLUSIVE
Me.Show
diDEV.Acquire diMouse.Acquire
ix = diSMouse.x iy = diSMouse.y iz = diSMouse.z
Timer1.Interval = 10 '设置敲击键盘的灵敏度 Timer1.Enabled = True End Sub
Private Sub Form_Unload(Cancel As Integer) '程序结束后释放DirectInput对象 diDEV.Unacquire diMouse.Unacquire End Sub
Private Sub Timer1_Timer() '获得当前的击键值 diDEV.GetDeviceStateKeyboard diState
For iKeyCounter = 0 To 255 '判断是否敲击了某键 If diState.Key(iKeyCounter) <> 0 Then Label1.Caption = iKeyCounter & " - 击键时间为: (" & Time & ")" End If Next
diMouse.GetDeviceStateMouse diSMouse If diSMouse.x <> 0 Then ix = diSMouse.x End If If diSMouse.y <> 0 Then iy = diSMouse.y End If If diSMouse.z <> 0 Then iz = diSMouse.z End If Form1.Caption = "X:" & ix & " Y:" & iy & " Z:" & iz DoEvents End Sub | 运行程序,敲击键盘的任意键,可以看到键值显示在了Label1上,而移动鼠标,当前鼠标坐标会显示在Form1的标题条上(光标的坐标原点是程序运行时光标所在的位置,而如果你的鼠标有滚轮的话,则Z坐标由你的滚轮的滚动所决定)。而不论窗口处于前台或者后台,击键和鼠标动作都会倍记录下来,你可以利用上面的程序稍加修改建立自己的鼠标键盘Hook程序。
|
|