CodeGo.net>我如何根据鼠标的运动绘制一个矩形?

我在这里找到了用于在表单上绘图的示例代码:

http://msdn.microsoft.com/en-us/library/aa287522(v=vs.71).aspx

作为此要求的后续措施(发现哪些控件位于矩形所描述的下方)
用户拖动鼠标):

There seems to be a mismatch between the location of my controls and the location of my MouseDown and -Up events

…我想向用户提供有关他们即将选择的内容的即时/持续反馈
(当/如果他们释放鼠标按钮).我不仅要在鼠标的后面画一条线
动作,但要画出由他们的鼠标争吵描述的矩形.

我在考虑MouseMove事件,再加上上面两个链接中的代码,可以解决问题,但是触发次数过多/是否会对性能产生恶意影响?如果是这样,那将是一个更可取的事件挂起,或者计时器将成为此方法?

UPDATE

这段代码改编自以下约翰的示​​例(唯一的区别是,引起StackOverflow的对base的调用已被注释掉,并且我将颜色从红色更改为黑色(无意引用Stendahl)),除了先前绘制的矩形外释放鼠标后再次显示. IOW,第一个矩形绘制得很完美-随鼠标单击(按预期方式)消失.但是,当我通过按下鼠标左键并向右向下拖动来描述第二个矩形时,第一个矩形会再次显示!并继续发生-记住每个先前绘制的矩形,并在绘制新矩形时将其重新显示.

公共局部类Form1:表单
{
    私人点? _开始;
    私人Rectangle _previousBounds;

public Form1()
{
    InitializeComponent();
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    _start = e.Location;
    //base.OnMouseDown(e); 

}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (_start.HasValue)
        DrawFrame(e.Location);

    //base.OnMouseMove(e); 

}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
    ReverseFrame();
    _start = null;
    //base.OnMouseUp(e); 
}

private void ReverseFrame() 
{ 
    ControlPaint.DrawReversibleFrame(_previousBounds, Color.Black, FrameStyle.Dashed); 
} 

private void DrawFrame(Point end) 
{ 
    ReverseFrame(); 

    var size = new Size(end.X - _start.Value.X, end.Y - _start.Value.Y); 
    _previousBounds = new Rectangle(_start.Value, size); 
    _previousBounds = this.RectangleToScreen(_previousBounds); 
    ControlPaint.DrawReversibleFrame(_previousBounds, Color.Black, FrameStyle.Dashed); 
} 

}

最佳答案
ControlPaint.DrawReversibleFrame()将做您想要的.性能通常不是问题,只需保持其小巧清洁即可.


编辑:添加了代码示例. StackOverflowException表示有问题-但看不到您的内容,无法直接回答.

private Point? _start;
private Rectangle _previousBounds;

protected override void OnMouseDown(MouseEventArgs e)
{
    _start = e.Location;
    base.OnMouseDown(e);
}

protected override void OnMouseMove(MouseEventArgs e)
{
    if( _start.HasValue ) {
        ReverseFrame();
        DrawFrame(e.Location);
    }

    base.OnMouseMove(e);
}

protected override void OnMouseUp(MouseEventArgs e)
{
    ReverseFrame();
    _start = null;
    base.OnMouseUp(e);
}

private void ReverseFrame()
{
    ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);

}
private void DrawFrame(Point end)
{
    ReverseFrame();

    var size = new Size(end.X - _start.Value.X, end.Y - _start.Value.Y);
    _previousBounds = new Rectangle(_start.Value, size);
    _previousBounds = this.RectangleToScreen(_previousBounds);
    ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);
}

转载注明原文:CodeGo.net>我如何根据鼠标的运动绘制一个矩形? - 代码日志