Problem with moving a winform using C#
My form doesn't have a title bar, so I am implementing the code to drag
the entire form around the screen. I am using the below code to do it, which works fine.
I have two panels in my form, Pa开发者_运维问答nelA
and PanelB
. During the startup I show
PanelA
where the dragging works perfectly. Later when the user clicks
the button in PanelA
, I need to make PanelA
invisible and show PanelB
However, the dragging does not work when PanelB
is shown. What's the
problem here?
private void SerialPortScanner_MouseUp(object sender, MouseEventArgs e)
{
this.drag = false;
}
private void SerialPortScanner_MouseDown(object sender, MouseEventArgs e)
{
this.drag = true;
this.start_point = new Point(e.X, e.Y);
}
private void SerialPortScanner_MouseMove(object sender, MouseEventArgs e)
{
if (this.drag)
{
Point p1 = new Point(e.X, e.Y);
Point p2 = this.PointToScreen(p1);
Point p3 = new Point(p2.X - this.start_point.X,
p2.Y - this.start_point.Y);
this.Location = p3;
}
}
Edit: I've realized that you're not asking about drag and drop, but rather about moving your form around the screen. (Thanks to @Veer.) I've edited your question to help clarify this. Drag and drop is a completely different thing, since it is dragging information from one control to another.
The same principle of my answer still applies though, since mouse events are also handled at the Control level - you might need to handle the mouse events from PanelB
as well.
精彩评论