首页 > 解决方案 > 当我移动一个控件时,客户端矩形是重复的 WinForms

问题描述

在此处输入图像描述

我有一个自定义控件,它允许您在屏幕上移动控件。出于某种原因,每当我移动控件时,都会复制 ClientRectangle。这是两个独立的矩形。我检查了我的代码没有复制任何对象,而且似乎没有。似乎客户端矩形粘在同一位置。

在我的图像中,我在客户端矩形周围绘制了红色以使其明显。

每当我调整控件的大小时,可见控件和孤立的客户矩形都会一起改变大小。我不明白为什么会这样。

这是在屏幕上移动控件的代码。

protected virtual void OnMouseMove(object sender, MouseEventArgs e)
{
    if (_selectedControl != null && _leftMouseDown)
    {
        if (_resizingControl)
        {
            Point pt = Cursor.Position;
            Point position = GetRelativePosition(_selectedControl);

            // Work out the expected right position and adjust the width so the right 
            // position matches. Do same with Bottom and Height
            int computedRight = _selectedControl.Left + PointToClient(pt).X;
            int increaseWidth = computedRight - _selectedControl.Right;
            _selectedControl.Width += increaseWidth - position.X;

            int computedBottom = _selectedControl.Top + PointToClient(pt).Y;
            int increaseHeight = computedBottom - _selectedControl.Bottom;
            _selectedControl.Height += increaseHeight - position.Y;

            ApplyTransformConstraints(_selectedControl);
        }

        else
        {
            Point pt = Cursor.Position;
            Point newlocation = new Point(PointToClient(pt).X - _offsetOnClientControl.X,
                PointToClient(pt).Y - _offsetOnClientControl.Y);

            _selectedControl.Location = newlocation;
        }

        _selectedControl.Refresh();
        _selectedControl.Invalidate();
    }

    Invalidate();
    Refresh();

    if (ControlFromPoint(e.Location) != null)
        Cursor = Cursors.Hand;
    else
        Cursor = Cursors.Default;
    if (_resizeRectangle.Contains(e.Location) || _resizingControl)
        Cursor = Cursors.SizeNWSE;
}

任何关于为什么会发生这种情况或可能解决它的想法将不胜感激。

标签: c#winformscustom-controlsgdi

解决方案


推荐阅读