简体   繁体   中英

VBA - Running a sub routine before excel application window is deactivated

I'm really stuck here. I'm trying to run a sub routine - copy range values - before the excel window is deactivated. I'm using 64bit vba and none of the current subroutine at the workbook level offer this solution. I would like to copy data any time Excel loses focus. Any ideas how this can be done ?

Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
    Wn.ActiveCell.Copy
End Sub

Unless you want to investigate subclassing, I don't see any other option but hooking to a WinEvent (which, as @Comitern says, is done using API functions).

The problem is that once you have hooks running, Excel can become a bit temperamental. Basically, if your code develops an error or you break the code during development, odds are the application will crash. Speaking personally, it drives me to insanity. As a result I created a class to protect myself as much as possible. It's a bit of a monster class so I've deleted all the code that doesn't pertain to your task, but it's still pretty big. I'm also ashamed to admit I'm still on 32 bit, so the APIs are for that. There are plenty of websites that show you the 64 bit equivalents, so you could just replace the relevant data types.

Ok, so here goes...

First, insert a class module (Insert ~> Class Module) and name it clsEventHookPair . It's just a data field class and code is:

Option Explicit

Public EventID As WinEventId
Public EventHook As Long

Second, insert another class module and name it clsWinEventListener . This is the class that manages the hooks:

Option Explicit

Private Const TAG As String = "clsWinEventListener"
Public Event WinEventHooked()
Public hWinEventHook As Long
Public WinEvent As WinEventId
Public hWnd As Long
Public idObject As Long
Public idChild As Long
Public dwEventThread As Long
Public dwmsEventTime As Long
Private mWinEventHookList As Collection
Private mTmpList As Collection

Public Sub AttachHook(evId As WinEventId)
    Dim ehp As clsEventHookPair

    'Check if hook is already running and remove it
    Me.DetachHook evId

    If mWinEventHookList Is Nothing Then
        Set mWinEventHookList = New Collection
    End If

    'Populate our hook list with new hook details
    Set ehp = New clsEventHookPair
    With ehp
        .EventID = evId
        .EventHook = modHook.HookUp(.EventID)
        mWinEventHookList.Add ehp, CStr(.EventID)
        Debug.Print TAG & ": Event hooked up [id=" & .EventID & ", hk=" & .EventHook & "]"
    End With
    Exit Sub

EH:
    Me.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Public Sub DetachHook(evId As WinEventId)
    Dim ehp As clsEventHookPair

    If Not mWinEventHookList Is Nothing Then
        'Check the hook is in our list
        On Error Resume Next
        Set ehp = mWinEventHookList(CStr(evId))
        On Error GoTo 0

        'Detach hook and remove from our list
        On Error GoTo EH
        If Not ehp Is Nothing Then
            With ehp
                modHook.Unhook .EventHook
                mWinEventHookList.Remove CStr(.EventID)
                Debug.Print TAG & ": Event unhooked [id=" & .EventID & ", hk=" & .EventHook & "]"
            End With
        End If
    End If
    Exit Sub

EH:
    Me.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Public Sub DetachAll()
    Dim ehp As clsEventHookPair

    'Remove all hooks from our list.
    'Mainly used in event of error being thrown.
    Debug.Print TAG & ": Commencing emergency detach..."
    If Not mWinEventHookList Is Nothing Then
        For Each ehp In mWinEventHookList
            Me.DetachHook ehp.EventID
        Next
    End If
    Set mWinEventHookList = Nothing
    Debug.Print TAG & ": Emergency detach complete."
End Sub

Public Sub PauseHooks()
    Dim ehp As clsEventHookPair

    'Detaches the hooks but keeps a record of the eventIds
    'so that we can attach hooks again on resume.
    'Note: we can't keep the old event hook ids as
    'we'll get new ones when reattached.
    On Error GoTo EH
    Debug.Print TAG & ": Pausing hooks ..."
    If Not mWinEventHookList Is Nothing Then
        Set mTmpList = New Collection
        For Each ehp In mWinEventHookList
            With ehp
                mTmpList.Add .EventID
                Me.DetachHook .EventID
            End With
        Next
        Set mWinEventHookList = Nothing
    End If
    Exit Sub

EH:
    Me.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Public Sub ResumeHooks()
    Dim evId As Variant

    'Re attach the 'paused' hooks
    On Error GoTo EH
    Debug.Print TAG & ": Resuming hooks ..."
    If Not mTmpList Is Nothing Then
        For Each evId In mTmpList
            Me.AttachHook CLng(evId)
        Next
        Set mTmpList = Nothing
    End If
    Exit Sub

EH:
    Me.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Public Sub ConsumeHookEvent()
    Dim isTargetHook As Boolean
    Dim ehp As clsEventHookPair

    If mWinEventHookList Is Nothing Then Exit Sub

    On Error GoTo EH
    For Each ehp In mWinEventHookList
        With ehp
            'Check the hook event is one we want and fire the class event
            'Shouldn't be needed but included in case we've left a rogue hook running.
            If .EventHook = Me.hWinEventHook And .EventID = Me.WinEvent Then
                RaiseEvent WinEventHooked
                Exit Sub
            End If
        End With
    Next
    Exit Sub

EH:
    Me.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Public Sub CountHooks()
    Dim c As Long

    'Used during development to ensure I don't break the code with hooks running
    If Not mWinEventHookList Is Nothing Then
        c = mWinEventHookList.Count
    End If
    Debug.Print TAG & ": " & c & " current hook" & IIf(c <> 1, "s.", ".")
End Sub

Private Sub Class_Initialize()
    'Assign this class to the modHook module
    'so that it can call the ConsumeHookEvent method
    Set modHook.Listener = Me

    'Remove after development.
    'I use this to remove all the hooks
    'if I want to break the code.
    frmHook.UseWhileDeveloping Me
End Sub

Private Sub Class_Terminate()
    'Remove the hooks
    Me.DetachAll
    Set modHook.Listener = Nothing
End Sub

Third, insert a new module and name in modHook . This is the module that contains the APIs and I've converted the eventId constants to enums so that I can exploit intellisense (not great programming technique but I just couldn't keep track of all my constants). Code is:

Option Explicit

Private Const TAG As String = "modHook"
Public Enum WinEventId
    EventSystemSound = &H1
    EventSystemAlert = &H2
    EventSystemForeground = &H3
    EventSystemMenuStart = &H4
    EventSystemMenuEnd = &H5
    EventSystemMenuPopUpStart = &H6
    EventSystemMenuPopUpEnd = &H7
    EventSystemCaptureStart = &H8
    EventSystemCaptureEnd = &H9
    EventSystemMoveSizeStart = &HA
    EventSystemMoveSizeEnd = &HB
    EventSystemContextHelpStart = &HC
    EventSystemContextHelpEnd = &HD
    EventSystemDragdropStart = &HE
    EventSystemDragDropEnd = &HF
    EventSystemDialogStart = &H10
    EventSystemDialogEnd = &H11
    EventSystemScrollingStart = &H12
    EventSystemScrollingEnd = &H13
    EventSystemSwitchStart = &H14
    EventSystemSwitchEnd = &H15
    EventSystemMinimizeStart = &H16
    EventSystemMinimizeEnd = &H17
    EventSystemDesktopSwitch = &H20
    EventSystemEnd = &HFF
    EventObjectCreate = &H8000
    EventObjectDestroy = &H8001
    EventObjectShow = &H8002
    EventObjectHide = &H8003
    EventObjectReorder = &H8004
    EventObjectFocus = &H8005
    EventObjectSelection = &H8006
    EventObjectSelectionAdd = &H8007
    EventObjectSelectionRemove = &H8008
    EventObjectSelectionWithin = &H8009
    EventObjectStateChange = &H800A
    EventObjectLocationChange = &H800B
    EventObjectNameChange = &H800C
    EventObjectDescriptionChange = &H800D
    EventObjectValueChange = &H800E
    EventObjectParentChange = &H800F
    EventObjectHelpChange = &H8010
    EventObjectDefactionChange = &H8011
    EventObjectAcceleratorChange = &H8012
    EventObjectInvoked = &H8013
    EventObjectTextSelectionChanged = &H8014
    EventObjectContentScrolled = &H8015
    EventSystemArrangmentPreview = &H8016
    EventObjectLiveregionChanged = &H8019
    EventObjectHostedObjectsInvalidated = &H8020
    EventObjectDragStart = &H8021
    EventObjectDragcancel = &H8022
    EventObjectDragcomplete = &H8023
    EventObjectDragEnter = &H8024
    EventObjectDragLeave = &H8025
    EventObjectDragDropped = &H8026
    EventObjectImeShow = &H8027
    EventObjectImeHide = &H8028
    EventObjectImeChange = &H8029
    EventObjectTextEditConversionTargetChanged = &H8030
    EventObjectEnd = &H80FF
End Enum
Private Declare Function SetWinEventHook Lib "user32.dll" _
    (ByVal eventMin As Long, _
    ByVal eventMax As Long, _
    ByVal hmodWinEventProc As Long, _
    ByVal pfnWinEventProc As Long, _
    ByVal idProcess As Long, _
    ByVal idThread As Long, _
    ByVal dwFlags As Long) As Long

Private Declare Function UnhookWinEvent Lib "user32" _
    (ByVal hWinEventHook As Long) As Long

Private mListener As clsWinEventListener

Public Property Set Listener(val As clsWinEventListener)
    Dim res As VbMsgBoxResult

    'Check if we have, and want, another instance of listener
    If Not mListener Is Nothing And Not val Is Nothing Then
        res = MsgBox(TAG & ": multiple instances of listener." & _
                     vbCrLf & vbCrLf & "Do you want to continue?", _
                     vbYesNo, "Developer warning")
        If res = vbNo Then
            mListener.DetachAll
            End
        End If
    End If

    Set mListener = val
End Property

Public Function HookUp(evId As WinEventId) As Long
    HookUp = SetWinEventHook(evId, evId, 0, AddressOf WinEventProc, 0, 0, 0)
End Function

Private Function WinEventProc _
    (ByVal hWinEventHook As Long, _
    ByVal WinEvent As Long, _
    ByVal hWnd As Long, _
    ByVal idObject As Long, _
    ByVal idChild As Long, _
    ByVal dwEventThread As Long, _
    ByVal dwmsEventTime As Long) As Long

    On Error GoTo EH
    'Pass event parameters to listener
    'and call listener's consume event method
    If Not mListener Is Nothing Then
        With mListener
            .hWinEventHook = hWinEventHook
            .WinEvent = WinEvent
            .hWnd = hWnd
            .idObject = idObject
            .idChild = idChild
            .dwEventThread = dwEventThread
            .dwmsEventTime = dwmsEventTime
            .ConsumeHookEvent
        End With
    End If
    Exit Function

EH:
    If Not mListener Is Nothing Then mListener.DetachAll
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
End Function

Public Sub Unhook(winEventHook As Long)
    Dim ret As Long

    ret = UnhookWinEvent(winEventHook)
End Sub

Fourth, this one's optional but I also have a Userform on show while I'm developing so that I can hit a button to remove the hooks before I break the code. It saved me on many occasions but up to you I guess. If you want it, insert a UserForm and name it frmHook . Add two buttons called btnUnHook and btnCount. The first is used to remove the hooks and the second just writes the number of running hooks to the immediate window. Basically, hit the unhook button whenever you want to exit the code. Code behind is:

Option Explicit
Private mListener As clsWinEventListener

Public Sub UseWhileDeveloping(lstnr As clsWinEventListener)
    Set mListener = lstnr
    Me.Show False
End Sub

Private Sub btnCount_Click()
    mListener.CountHooks
End Sub

Private Sub btnUnHook_Click()
    mListener.DetachAll
End Sub

Private Sub UserForm_Terminate()
    mListener.DetachAll
End Sub

And finally, you can access this lot in any object module. Typically, people hook up at the Workbook_Open event, so I've done the same in the code below:

Option Explicit

Private WithEvents mListener As clsWinEventListener

Private Sub mListener_WinEventHooked()
    On Error GoTo EH

    'Handler for the hook event
    If mListener.WinEvent = EventSystemForeground Then
        If mListener.hWnd <> Application.hWnd Then
            mListener.PauseHooks 'don't need this but I remove hooks while working on sheets
            MsgBox "Excel lost focus."
            '... code goes here ...
            mListener.ResumeHooks 're-attch the hooks
        End If
    End If
    Exit Sub

EH:
    If Not mListener Is Nothing Then mListener.DetachAll
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    'Remove all hooks before close
    If Not mListener Is Nothing Then
        mListener.DetachAll
    End If
End Sub

Private Sub Workbook_Open()
    On Error GoTo EH
    Set mListener = New clsWinEventListener

    'Hook up to desired events here
    mListener.AttachHook EventSystemForeground
    Exit Sub

EH:
    If Not mListener Is Nothing Then mListener.DetachAll
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM