请看以下代码:
-----------------------------------------------------------------
    Dim filePath As String    filePath = "X:\XXX\XXX.exe"
    If Len(Dir$(filePath)) = 0 Then Exit Sub
    
    Dim pId As Long
    pId = Shell(filePath, vbNormalFocus)
    If pId = 0 Then Exit Sub
    
    Dim pHnd As Long
    pHnd = OpenProcess(SYNCHRONIZE, 0&, pId)
    If pHnd = 0 Then Exit Sub
    
    Dim hInstance As Long
    '/////////////////////////////////////////////////////////////
    hInstance = ???
    hHook = SetWindowsHookEx(WH_CALLWNDPROC, AddressOf HookProc, hInstance, 0&)
    '/////////////////////////////////////////////////////////////
    
    Dim lRet As Long
    Do
        lRet = WaitForSingleObject(pHnd, 0&)
        DoEvents
    Loop While lRet = WAIT_TIMEOUT
    
    Call UnhookWindowsHookEx(hHook)
    Call CloseHandle(pHnd)
-----------------------------------------------------------------
请大家看//////////之间的代码:
1、怎样取得这个 hInstance 呢?
2、我把 hHook = SetWindowsHookEx(WH_CALLWNDPROC, AddressOf HookProc, hInstance, 0&) 代码中的 hInstance 换成 App.hInstance 也会报错,为什么呢?

解决方案 »

  1.   

    你想拦截目标进程所有SendMessage的消息吗?那样的话,貌似要标准DLL的帮助哦.
      

  2.   

    '如果原来有窗口的句柄就可以这样获取hInstance了
    '不过你的情况麻烦点~~~~~~~~~
    Private Const GWL_HINSTANCE As Long = -6Private Declare Function GetWindowLong Lib "user32.dll" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As LonghInstance=GetWindowLong(hWnd,GWL_HINSTANCE)
    '下面是根据PID获取句柄hWnd(API-Guide里面copy的~~~)
    Private Const GW_HWNDNEXT = 2Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As Long, ByVal lpWindowName As Long) As Long
    Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
    Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As LongFunction InstanceToWnd(ByVal target_pid As Long) As Long
        Dim test_hwnd As Long, test_pid As Long, test_thread_id As Long
        'Find the first window
        test_hwnd = FindWindow(ByVal 0&, ByVal 0&)
        Do While test_hwnd <> 0
            'Check if the window isn't a child
            If GetParent(test_hwnd) = 0 Then
                'Get the window's thread
                test_thread_id = GetWindowThreadProcessId(test_hwnd, test_pid)
                If test_pid = target_pid Then
                    InstanceToWnd = test_hwnd
                    Exit Do
                End If
            End If
            'retrieve the next window
            test_hwnd = GetWindow(test_hwnd, GW_HWNDNEXT)
        Loop
    End Function
      

  3.   

    如果hook的目标不是本程序
    那么必需把回调函数写进dll,然后载入这个DLL,取得hinstance值
      

  4.   

    GetMoudleHandle不就能获得hInstance吗?