Problem : Intercepting WM_ACTIVATE message for any window (detecting activation with hooks/subclassing)

Problem : Intercepting WM_ACTIVATE message for any window (detecting activation with hooks/subclassing)

hello,

i currently need to detect when a certain application’s window is activated and deactivated.  this is a 3rd party window, not one that is part of my vb.net project.  i have read a bit about hooks and subclassing, but i have not seen a concrete example of this in vb.net.  i would basically like to do what Spy++ does for message logging.  i can get the window’s basic attributes like hWnd just fine.  i am just having problem’s hooking into the messages.  i have successfully written code which intercepts messages from my own forms, but when i try to use a 3rd party window, i am unsuccessful.  the APIs i have been using are SetWindowLong and CallWindowProc.  please advise.

thanks,


 

Solution: Intercepting WM_ACTIVATE message for any window (detecting activation with hooks/subclassing)

I think this works in .NET as well 🙂
It turned out to be much simpler than I thought. Here’s the code:

‘ Shell Events Constants
Public Enum ShellEvents
HSHELL_WINDOWCREATED = 1
HSHELL_WINDOWDESTROYED = 2
HSHELL_ACTIVATESHELLWINDOW = 3
HSHELL_WINDOWACTIVATED = 4
HSHELL_GETMINRECT = 5
HSHELL_REDRAW = 6
HSHELL_TASKMAN = 7
HSHELL_LANGUAGE = 8
HSHELL_ACCESSIBILITYSTATE = 11
End Enum

‘ API Declares
Public Declare Function RegisterWindowMessage Lib “user32.dll” Alias “RegisterWindowMessageA” (ByVal lpString As String) As Integer
Public Declare Function DeregisterShellHookWindow Lib “user32” (ByVal hWnd As IntPtr) As Integer
Public Declare Function RegisterShellHookWindow Lib “user32″ (ByVal hWnd As IntPtr) As Integer

Imports System.Runtime.InteropServices

Public Class Form1
Inherits System.Windows.Forms.Form

Private uMsgNotify As Integer

#Region ” Windows Form Designer generated code ”

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘ This will register the ShellHook event messages between the shell and our application.
‘ The uMsgNotify is then used to communicate between the shell and our application whenever any
‘ of the shell events are fired such as an app starting up, shutting down, activating, minimizing, etc
uMsgNotify = RegisterWindowMessage(“SHELLHOOK”)
‘ This basically registers our window to receive the shell events
Call RegisterShellHookWindow(Me.Handle)
End Sub

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = uMsgNotify Then
Select Case m.WParam.ToInt32
Case ShellEvents.HSHELL_WINDOWACTIVATED
Debug.WriteLine(“window activated”)
End Select
End If
MyBase.WndProc(m)
End Sub