'用 API 函数配合控件 Timer1,不管活动窗口是那一个,也不管是不是本程序窗口,都能检测键盘和鼠标状态 '运行后,请留意本窗口标题栏给出的信息 Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer Private Declare Function GetCursorPos& Lib "user32" (lpPoint As PointAPI) Private Type PointAPI X As Long: Y As Long End Type Dim ctTimer As Single Private Sub Form_Load() Timer1.Enabled = True: Timer1.Interval = 100 End Sub Private Sub Timer1_Timer() Dim T As Single T = Format(Timer - ctTimer, "0.0") If KeyOrMouse() Then T = 0: ctTimer = Timer Me.Caption = "鼠标和键盘未动时间:" & T & " 秒" End Sub Private Function KeyOrMouse() As Boolean Static x0 As Long, y0 As Long Dim nMouse As PointAPI, I As Long, dl As Long '检测鼠标 是否移动 Call GetCursorPos(nMouse) '获取当前鼠标位置 If x0 <> nMouse.X Or y0 <> nMouse.Y Then KeyOrMouse = True x0 = nMouse.X: y0 = nMouse.Y If KeyOrMouse Then Exit Function '检测键盘 是否按动 For I = 0 To 255 dl = GetAsyncKeyState(I) If dl <> 0 Then KeyOrMouse = True: Exit Function Next End Function |