Search code examples
.netvb.netinteropwndproc

Hosting .net control in native window


I am hosting .NET ListView control in native window using SetParent:

Public Class LVControl
    Public Shared Lv As New ListView

    Shared Sub LvInit(ByVal hWnd As IntPtr)
        Lv.Size = New System.Drawing.Size(256, 256)
        Lv.Dock = Windows.Forms.DockStyle.Fill
        Lv.Show()
        NativeMethods.SetParent(Lv.Handle, hWnd)
    End Sub

...
End Class

How can I intercept WM windows messages sent by host window to it's child windows (my Listview control)? Since I create control in runtime and I have no parent form for it (and having it is not an option) how can I implement overridable WndProc function? It says "it cannot be declared because it does not override a sub in base class" and I would like to use managed code here...

P.s: Now I'am playing with implementation of NativeWindow class for parent native window of my ListView control, but dont know how to do it well and am I in the right direction?

UPDATE

Thanks to comments, I got it working:

Public Class myListView
    Inherits ListView
    Protected Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            Dim hParent As IntPtr '= get parent hWnd here
            cp.Parent = hParent
            Return cp
        End Get
    End Property

    Protected Overrides Sub WndProc(ByRef m As Message)
        'handle messages here
        MyBase.WndProc(m)
    End Sub
End Class 

Now I have last question about how to pass a parameter containing parent hWnd into CreateParams property? Obtaining parent hWnd depends on some conditions that I wouldn't want to be hardcoded here, they obtained from incoming parameters.


Solution

  • It's pretty easy. Just inherit a new ListView class from the base ListView and override the WndProc sub (like Hans wrote in his comment):

    Public Class LVControl
        Public Shared Lv As New MyListView
    
        Shared Sub LvInit(ByVal hWnd As IntPtr)
            Lv.Size = New System.Drawing.Size(256, 256)
            Lv.Dock = Windows.Forms.DockStyle.Fill
            Lv.Show()
            NativeMethods.SetParent(Lv.Handle, hWnd)
        End Sub
    End Class
    
    Public Class MyListView
        Inherits ListView
    
        Protected Overrides Sub WndProc(ByRef m As Message)
            MyBase.WndProc(m)
            'WndProc code here
        End Sub
    End Class