2

Goal: To make use of windows events/hooks to immediately detect Windows foreground window changing (focus change) WITHOUT using a timer. This is for a global macros program, where I want specific keystrokes/mousebutton clicks to register events only if a certain window is active (rather than checking the foreground window every time a key or mousebutton is pressed).

I know how to use GetForegroundWindow to get the handle of the foreground window and GetActiveWindowText to get the title, and I know I COULD use these in a timer to keep it constantly updated. However, I would really rather make use of windows messages to accomplish this if possible (other related topics on this site have made use of timers, not windows messages).

I have tried WM_ACTIVATE, WM_ACTIVATEAPP, and WM_SHOWWINDOW but these don't appear to be global (I think only low-level hooks like keyboard hooks can be global), so they do not fire if I change window focus such as from Google Chrome to Calculator or Notepad. Do I need to register a hook or something in order to use a global form of these messages, or is that actually not possible?

Goal would be something like this:

    Protected Overrides Sub WndProc(ByRef m As Message)
    MyBase.WndProc(m)
    Select Case m.Msg
       Case WM_ACTIVATE 'Whatever message that can be used to determine windows focus change
            Dim caption As New System.Text.StringBuilder(256)
            Dim hWnd As IntPtr = GetForegroundWindow()
            GetActiveWindowText(hWnd, caption, caption.Capacity)
            Me.Text = caption.ToString
    End Select
End Sub
NotJehov
  • 43
  • 7
  • You need a WH_SHELL hook to tell you what is going on with the rest of the processes on the desktop. You cannot write such a hook in managed code, it requires a DLL that can be injected into every process. Having to have both a 32-bit and a 64-bit version of that DLL makes it extra complicated. Get ahead by learning C++ first. – Hans Passant Dec 12 '13 at 16:31
  • I see. I looked into some other methods, but any other method of attaching a global hook in managed code like this were hacks (like attaching a hook to the desktop explorer). I guess I will simply check the active window on keypress/mouseup. Thanks – NotJehov Dec 12 '13 at 23:25

0 Answers0