Search code examples
.netdelphiwinapicomsendmessage

How to get Handle of a form that hosts a COM-Control


I have a visual DotNet-Control that I use as COM-Control in a Delphi project.
Now I want to get the handle of the delphi form that hosts this DotNet-component in DotNet. Sure - i could pass the Form's handle from Delphi to DotNet using something like a setParentHandle(pHandle: hwnd); method that I define, but this is not the way I want to do it here.

Is there any Winapi call that can give me the handle of a component that I draw something on in DotNet?

I want to use this handle in order to send Messages that can not be handled by the DotNetComponent itself to the Delphi Form.


Solution

  • I resolved this using the GetParent method of WinApi just like this in C#.

    [DllImport("user32.dll")]
    private static extern IntPtr GetParent(IntPtr hWnd);
    
    protected override void WndProc(ref Message m){
    
        // 0x20a is the Message constant for WM_MOUSEWHEEL (Scrolling on your control)
        if(m.Msg == 0x20a){
          IntPtr hWnd= GetParent(this.Handle);
          SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
        }
        else
            base.WndProc(ref m);
    }
    

    Remark: Forwarding all messages to the parent control will break your Control since it won't receive its own messages any longer.