This is a solution in addition to Mark Salsbery's. His code works, but when you have a control on the area that your window is dragged when you perform a mousedown, it's events don't work because the CaptureMouse() function blocks it.
For example, I have a "close" button (which is actually a label), but it's mousedown event won't work because the CaptureMouse() function somehow blocks it.
Solution is to use capturemouse function in the "OnMouseMove" event. So if mouse doesn't move after mousedown event, capturemouse will not block other controls' events.
private bool inDrag = false;
private Point anchorPoint;
private bool iscaptured = false;
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
anchorPoint = PointToScreen(e.GetPosition(this));
inDrag = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (inDrag) {
if (!iscaptured) {
CaptureMouse();
iscaptured = true;
}
Point currentPoint = PointToScreen(e.GetPosition(this));
this.Left = this.Left + currentPoint.X - anchorPoint.X;
this.Top = this.Top + currentPoint.Y - anchorPoint.Y;
anchorPoint = currentPoint;
}
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (inDrag) {
inDrag = false;
iscaptured = false;
ReleaseMouseCapture();
}
}