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

10,398

Solution 1

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.

Solution 2

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...
}
Share:
10,398
Mark Wager-Smith
Author by

Mark Wager-Smith

Updated on June 27, 2022

Comments

  • Mark Wager-Smith
    Mark Wager-Smith almost 2 years

    This is a Windows Forms / .Net C# question.

    I have a borderless windows whose transparency key and background color make it completely transparent. Inside the window are a couple of user controls.

    I want to be able to move the window. I know how to do this on the parent window, but my problem is that the child controls are the only thing visible and thus the only thing click-able.

    The question is: how can I pass certain messages up to the Parent so the Parent can move when the right mouse button is down and the mouse is moving on any one of the child controls?

    Or maybe you can suggest another way?

    Thanks for the help.

    Mark