Kit22092 Kit22092 - 26 days ago 15
C# Question

C# Winform - Keep MouseDown and join to other object the object MouseMove not work

When MouseDown on objectA then mousemove to objectB , the objectB(mousemove handle)cannot calling.

How to let other object detect the mousemovehandle , when mousedown before enter the object area.

public Test()
{
InitializeComponent();
this.Size = new Size(500, 500);
Panel pl = new Panel();
pl.Size = new Size(200, 200);
pl.Location = new Point(0, 0);
pl.BackColor = Color.Pink;

Label lb = new Label();
lb.Text = "Keep MouseDown and move to Panel2 , Panel2 MouseMoveHandler not work";
lb.Dock = DockStyle.Fill;
pl.Controls.Add(lb);

TextBox tb = new TextBox();
tb.Multiline = true;
tb.Size = new Size(400, 100);
tb.Location = new Point(0,300);

Panel pl2 = new Panel();
pl2.Size = new Size(100, 100);
pl2.Location = new Point(0, 0);
pl2.BackColor = Color.Red;
pl2.Location = new Point(300, 0);
pl2.MouseMove += new MouseEventHandler(delegate (object o, MouseEventArgs a)
{
tb.AppendText(a.X + "," + a.Y);
});

this.Controls.Add(pl);
this.Controls.Add(pl2);
this.Controls.Add(tb);
}

Jcl Jcl
Answer

What you see is the standard behaviour. It's the only way you could get MouseMove events for an object while having the mouse down if you move the mouse outside that object.

If you want to find out which control is under the cursor at any point in time (you can do it in your MouseMove event if needed), you can use this code:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(Point pnt);

public static Control GetControlUnderCursor() {
  var handle = WindowFromPoint(Control.MousePosition);
  if (handle != IntPtr.Zero)
    return Control.FromHandle(handle);
  return null;
}

You could use this code in the form's MouseMove event if you set the form's Capture property to true (that's what is happening on your control when you hold the mouse button down) also and you can check Control.MouseButtons to find out which mouse buttons are pressed if needed..