Skip to content

Instantly share code, notes, and snippets.

@jeff123wang
Created April 6, 2022 15:13
Show Gist options
  • Save jeff123wang/1be0203cec98375c46903fdec491daad to your computer and use it in GitHub Desktop.
Save jeff123wang/1be0203cec98375c46903fdec491daad to your computer and use it in GitHub Desktop.
Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" _
() As Long
Private Declare PtrSafe Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" _
(ByVal idHook As Long, ByVal lpfn As LongPtr, ByVal hmod As LongPtr, ByVal dwThreadId As Long) As LongPtr
Private Declare PtrSafe Function SetDlgItemText Lib "user32" Alias "SetDlgItemTextA" _
(ByVal hDlg As LongPtr, ByVal nIDDlgItem As Long, ByVal lpString As String) As Long
Private Declare PtrSafe Function CallNextHookEx Lib "user32" _
(ByVal hHook As LongPtr, ByVal ncode As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Private Declare PtrSafe Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As LongPtr) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" _
Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Declare PtrSafe Function GetWindowText Lib "user32" _
Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Public Declare PtrSafe Function GetWindowTextLength Lib "user32" _
Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Public Declare PtrSafe Function SetWindowPos Lib "user32" _
(ByVal hwnd As Long, _
ByVal hWndInsertAfter As Long, _
ByVal x As Long, _
ByVal y As Long, _
ByVal cx As Long, _
ByVal cy As Long, _
ByVal wFlags As Long) As Long
Private hHook As LongPtr
Private Const WH_CBT = 5 ' hook type
Private Const HCBT_ACTIVATE = 5 ' activate window
Private Const IDYES = 6
Private Const HCBT_MOVESIZE = 0
Private Const SWP_NOSIZE = &H1
Private Const SWP_NOACTIVATE = &H10
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Function MsgBoxCustom_Proc(ByVal lMsg As Long, ByVal wParam As Long, ByVal lParam As LongPtr) As LongPtr
Dim title As String
title = getNameFromHwnd(wParam)
If lMsg = HCBT_ACTIVATE And title = "Hellow" Then
Debug.Print "activated"
SetWindowPos wParam, 0, 10, 10, 200, 200, SWP_NOSIZE Or SWP_NOACTIVATE
End If
MsgBoxCustom_Proc = CallNextHookEx(hHook, lMsg, wParam, lParam)
End Function
Public Sub addHook()
hHook = SetWindowsHookEx(WH_CBT, AddressOf MsgBoxCustom_Proc, 0, GetCurrentThreadId)
MsgBox "test", vbSystemModal, "Hellow"
If hHook <> 0 Then UnhookWindowsHookEx hHook ' this is very important
End Sub
Public Function getNameFromHwnd(hwnd As Long) As String
Dim title As String * 255
Dim tLen As Long
tLen = GetWindowTextLength(hwnd)
GetWindowText hwnd, title, 255
getNameFromHwnd = Left(title, tLen)
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment