Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

vb.net subclassing


ghost's Avatar
0 0

Hi, I'm trying to subclass windows using vb.net.

    Declare Function GetForegroundWindow Lib "user32" Alias "GetForegroundWindow" () As Integer
    Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer, ByVal dwNewLong As NewWindowProcDelegate) As Integer
    Declare Function SetWindowLong2 Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
    Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Integer, ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

    Public Const GWL_WNDPROC As Integer = (-4)

    Dim foregroundHandle As Integer
    Dim oldProc As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Timer1.Enabled = True
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Enabled = False
        foregroundHandle = GetForegroundWindow()
        ListBox1.Items.Add(foregroundHandle)
        oldProc = SetWindowLong(foregroundHandle, GWL_WNDPROC, AddressOf NewWindowProc)
        ListBox1.Items.Add(oldProc)
    End Sub

    Public Delegate Function NewWindowProcDelegate(ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

    Public Function NewWindowProc(ByVal hwnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
        ListBox1.Items.Add("Message found")
        Try
            ListBox1.Items.Add("Msg: " & msg & "  wParam: " & wParam & "  lParam: " & lParam)
        Catch ex As Exception

        End Try

        Return CallWindowProc(oldProc, hwnd, msg, wParam, lParam)
    End Function

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        SetWindowLong2(foregroundHandle, GWL_WNDPROC, oldProc)
    End Sub
End Class```

The problems is that oldProc = SetWindowLong(foregroundHandle, GWL_WNDPROC, AddressOf NewWindowProc) returns 0, wich means that the function fails.

Does anyone have a soulotion to this problem?