C# WinForms dragging controls with mouse
I'm making a calendar From in C# using WinForms. I've put it together using a two-dimensional array of Panels, and inside them I have a List<> of custom controls which represent appointments.
The user needs to be able to drag appointment controls from one Panel to another (from day to day).
The custom control has a MouseDown and MouseUp event, which passes a message up from the control to the Parent.Parent (custom control -> day panel -> calendar form) and calls public methods StartDragging() and StopDragging() respectively.
Inside these methods, I make a clone of the custom control and add it to the 开发者_Python百科Form, and store it in a global variable in the form which is called DraggedControl.
The Form has an event handler for MouseMove which goes like this:
void Calendar_MouseMove(object sender, MouseEventArgs e)
{
if (DraggedControl == null)
return;
DraggedControl.Location = PointToClient(MousePosition);
Refresh();
}
There are two problems, however:
- First of all, the custom control is under everything else. I can see it being added and removed on MouseDown and MouseUp, but it is being added at 0,0 under the panels and day Labels.
- Secondly, it does not appear to be moving with the MouseMove at all. I have a feeling this might be because I am moving the mouse with the button pressed, and this would represent a drag action rather than a basic MouseMove.
If I remove the MouseUp code, the control does drag with the mouse, however as soon as the mouse enters the panels (which the control is, sadly, underneath), the drag action stops.
What would you suggest I do? I suspect there is probably a better way to do what I am trying to do.
custom control is under everything else
bring it on top:
DraggedControl.BringToFront();
it does not appear to be moving with the MouseMove at all
Control, which handled MouseDown
event, captures mouse input and receives all following MouseMove
events until it releases mouse input on MouseUp
event, that's why Calendar_MouseMove()
is not called. Handle MouseMove
event for the same control, which generated MouseDown
event.
精彩评论