How to pass messages from a child user-control to the parent

五迷三道 提交于 2019-12-01 08:29:21

You can achieve your goal even without SendMessage using System.Windows.Forms.Message class. If you have done dragging I guess you are familiar with WM_NCLBUTTONDOWN message. Send it to you parent from your control's MouseDown event.

Here is an example for moving the form clicking on control label1. Note the first line where sender is used to release the capture from clicked control. This way you can set this handler to all controls intended to move your form.

This is complete code to move the form. Nothing else is needed.


public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

private void label1_MouseDown(object sender, MouseEventArgs e)
{
      (sender as Control).Capture = false;
      Message msg = Message.Create(Handle, WM_NCLBUTTONDOWN, (IntPtr)HT_CAPTION, IntPtr.Zero);
      base.WndProc(ref msg);
}

Hope this helps.

I think the easiest way is to add this event to your child controls:

/// <summary>
/// The event that you will throw when the mouse hover the control while being clicked 
/// </summary>
public event EventHandler MouseRightClickedAndHoverChildControl;

After, all the parent have to do is to subscribe to those events and make the operations to move the Parent:

ChildControl.MouseRightClickedAndHoverChildControl += OnMouseHoverChildControl;

private void OnMouseHoverChildControl(object sender, EventArgs e)
{
    //do foo...
}

You need to call the SendMessage API function to send mouse messages to your parent control.

It would probably be easiest to do this by overriding your control's WndProc method.

I had exactly this question... but came up with a different answer. If you have the Message in your WndProc, you can just change the handle to your Parent's handle and then pass it along.

I needed to do this in our derived TextBox... TextBox eats scroll wheel events even when its ScrollBars are set to None. I wanted those to propagate on up to the Form. So, I simply put this inside the WndProc for my derived TextBox:

            case 0x020A: // WM_MOUSEWHEEL
            case 0x020E: // WM_MOUSEHWHEEL
                if (this.ScrollBars == ScrollBars.None && this.Parent != null)
                    m.HWnd = this.Parent.Handle; // forward this to your parent
                base.WndProc(ref m);
                break;

            default:
                base.WndProc(ref m);
                break;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!