调整控件大小时的奇怪效果

时间:2015-05-21 07:09:39

标签: c# winforms controls

我创建了两个自定义控件。矩形和椭圆。我可以通过拖动鼠标移动它们,但我也想调整它们的大小。矩形调整大小工作正常,但椭圆的大小调整会产生奇怪的效果。当我在调整大小后单击椭圆并再次拖动它时,椭圆再次看起来正常。这里带有gif的链接显示了我对“奇怪”效果http://gyazo.com/319adb7347ed20fe28b6b93ced8744eb的意思。怎么修复这个效果?此外椭圆在角落有一些白色空间,因为它是以矩形形状绘制的,也许有办法解决这个问题?

Control.cs

class Ellipse : Control
{
    Point mDown { get; set; }

    public Ellipse()
    {
        MouseDown += shape_MouseDown;
        MouseMove += shape_MouseMove;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // Draw a black ellipse in the rectangle represented by the control.
        e.Graphics.FillEllipse(Brushes.Black, 0, 0, Width, Height);

        //Set transparent background
        SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.DoubleBuffer, true);
        this.BackColor = Color.Transparent;
    }  

    public void shape_MouseDown(object sender, MouseEventArgs e)
    {
        mDown = e.Location;
    }

    public void shape_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            Location = new Point(e.X + Left - mDown.X, e.Y + Top - mDown.Y);
        }
    }

    /* Allow resizing at the bottom right corner */
    protected override void WndProc(ref Message m)
    {
        const int wmNcHitTest = 0x84;
        const int htBottomLeft = 16;
        const int htBottomRight = 17;
        if (m.Msg == wmNcHitTest)
        {
            int x = (int)(m.LParam.ToInt64() & 0xFFFF);
            int y = (int)((m.LParam.ToInt64() & 0xFFFF0000) >> 16);
            Point pt = PointToClient(new Point(x, y));
            Size clientSize = ClientSize;
            if (pt.X >= clientSize.Width - 16 && pt.Y >= clientSize.Height - 16 && clientSize.Height >= 16)
            {
                m.Result = (IntPtr)(IsMirrored ? htBottomLeft : htBottomRight);
                return;
            }
        }
        base.WndProc(ref m);
    }
  } 
}

Form1.cs的

通过这种方式,我创建了Ellipse这段代码来自panel_MouseUp (object sender, MouseEventArgs e)方法。

case Item.Ellipse:
var el = new Ellipse();
panel.Controls.Add(el);
el.Location = new Point(x, y);
el.Width = (xe - x);
el.Height = (ye - y);
break;

1 个答案:

答案 0 :(得分:3)

您需要告诉控件在调整大小时完全重绘自己。将其ResizeRedraw属性设置为true。您还需要小心在Paint事件处理程序中执行的操作,它应该永远不会有全局状态副作用。如上所述,当我尝试时,你的控件迅速撞坏了设计师。

从OnPaint中删除最后两行,并使您的构造函数如下所示:

public Ellipse() {
    MouseDown += shape_MouseDown;
    MouseMove += shape_MouseMove;
    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    this.BackColor = Color.Transparent;
    this.DoubleBuffered = true;
    this.ResizeRedraw = true;
}

通过重写OnMouseDown / Move()而不是使用事件来进一步改进这一点。并查看ControlPaint.DrawGrabHandle()以使调整大小更直观。