Search code examples
c#wndproc

How can I intercept wndproc of parent form in usercontrol


Is there method for receive wndproc of parent form in user control?

I'm making titlebar user control and I want to receive windows message about form resize.

(this form is formborderstyle=none.)


Solution

  • Since the WndProc function doesn't intercept all windows messages I got used to create a MessageFilter, since this one does filter every windows message. So at first you create a new class which will implement the interface IMessageFilter.

    class MessageFilter : IMessageFilter
    {
        public static IntPtr MyHandle { get; set; }
    
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == /*windows code for resizing*/ && m.HWnd == MyHandle)
            {
                //do what you desire
                return true;
            }
            else
                return false;
        }
    }
    

    So you filter all messages and wait until the message contains the code for resizing and that the code aims to your specific window. In Windows all controls like a button, form, ... have a handle, which is unique. The handle is used to tell to which specific control the windows message shell be send, so we can use this as a criterion for the resize detection.

    MyHandle shell contain the window handle of your form you want to listen to it's resizing. So you should set it e.g. in the constructor:

    MessageFilter.MyHandle = this.Handle;
    

    Now we created our own MessageFilter, now we have to add it to your application that it listens to the windows messages. This should be set in the constructor.

    MessageFilter msgFilter = new MessageFilter();
    
    Application.AddMessageFilter(msgFilter);