Forward Mouse event in Main window to its controls
I have a problem about how to forward mouse events from my main window to its controls.
I create a user control called Sprite control. It must be able to move whenever it is dragged.
So the Sprite control will handle MouseDown, MouseMove and MouseUp events as follows
========= begin Sprite control =========
Boolean isDrag = false;
private void Sprite_MouseDown(object sender, MouseEventArgs e)
{
this.Left = this.Left + e.X - this.Width / 2;
this.Top = this.Top + e.Y - this.Height / 2;
isDrag = true;
}
private void Sprite_MouseMove(object sender, MouseEventArgs e)
{
if (isDrag)
{
this.Left = this.Left + e.X - this.Width / 2 ;
this.Top = this.Top + e.Y - this.Height / 2;
}
}
private void Sprite_MouseUp(object sender, MouseEventArgs e)
{
isDrag = false;
}
private void Sprite_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Brushes.Blue, 2), ClientRectangle);
}
========= end Sprite control =========
I add the Sprite control into my main window, it is set to invisible at design time. It will be visible if the users click and drag everywhere in the main window. After releasing the mouse, it becomes invisible again.
In my main window, as a consumer of the Sprite control, the code is as follows
========= begin main window =========
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
sprite1.Visible = false;
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
sprite1.Location = new Point(e.X - sprite1.Width / 2, e.Y - sprite1.Height / 2);
sprite1.Visible = true;
}
========= end main window =========
My problem is that the Sprite's mouse event handlers never get executed when users are doing click and drag on the main window (but before releasing the mouse).
So I need to forward the mouse event from the main window to the Sprite control here.
How to do this as easy as possible without using hook mechanism or any complicated ways.
NOTE:
I want to make the Sprite control as compact as possible for the consumer (Main window in this case) so its position must be handled by its own mouse events rather than by the consumer.
Thank you in advance.
Andi Setiawan
|