2014-02-18 2 views
0

Я хочу переместить прямоугольник на экран. Это код, что я сделал в то время:Как перемещать прямоугольник с помощью мыши

internal class GraphicContainer : Control 
{ 
    //---------------------METHODS--------------------- 
    public GraphicContainer(Control control, string text, int left, int top) 
     : base(control, text, left, top, 400, 200) 

    protected override void OnPaint(PaintEventArgs pe) 
    { 
     // Call the OnPaint method of the base class. 
     base.OnPaint(pe); 

     // Declare and instantiate a new pen. 
     Pen pen = new Pen(Color.Fuchsia, 15); 
     SolidBrush myBrush= new System.Drawing.SolidBrush(Color.HotPink); 
     // Draw an aqua rectangle in the rectangle represented by the control. 
     //pe.Graphics.DrawRectangle(pen, new Rectangle(this.Location,this.Size)); 
     Rectangle blublublu = new Rectangle(this.Location, this.Size - new Size(25, 25)); 
     pe.Graphics.DrawRectangle(pen,blublublu); 
     pe.Graphics.FillRectangle(myBrush,blublublu); 
    } 

    protected override void OnMouseMove(MouseEventArgs e) 
    {   
    } 

    protected override void OnClick(EventArgs e) 
    { 
    } 
} 

Я искал много и не нашли то, что код я должен написать в «OnMouseMove» и «OnClick» для того, чтобы мышь, чтобы двигаться.

+0

Почему бы просто не сохранить координаты, указанные в e, из OnMouseMove и использовать их для заполнения blublublu. – Rob

+0

Звучит как какой-то Drag'n'Drop. В дикой природе есть множество учебников. – TGlatzer

ответ

0

Ryan Reynolds!

Сделать кубблобласти полем. Вы должны будете использовать MouseMove, MouseUp, MouseDown:

Rectangle blublublu = new Rectangle(...); // possibly init in constructor 

    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      Capture = true; 
      _x = e.X; // remember coords 
      _y = e.Y; 
     } 
     base.OnMouseDown(e); 
    } 

    protected override void OnMouseUp(MouseEventArgs e) 
    { 
     Capture = false; 
     base.OnMouseUp(e); 
    } 

    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      blublublu.X += _x - e.X; // not tested, maybe use Rectangle.Offset or create a new Rectangle 
      blublublu.Y += _y - e.Y; 
      Invalidate(); 
     } 
    } 

Когда мышь вниз, вы захватить его (получить MouseMove события, даже если мышь она вне контроля) и запомнить координаты. При перемещении мыши вы меняете текущие координаты blublublu на разницу (сохраненная позиция мыши минус текущая) и вызываете Invalidate.

0

Вы можете внести переменную Location и аннулировать контроль над перемещением мыши. Кроме того, это произойдет только при нажатии левой кнопки мыши

Обратите внимание, что я не буду переопределять OnMouseMove, а скорее подписаться на мероприятие, добавив другой обработчик.

Point mouseLocation; 

public GraphicContainer(Control control, string text, int left, int top) 
    : base(control, text, left, top, 400, 200) { 
    //prevents flickering 
    this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); 

    //subscribes to mousemove 
    this.MouseMove += (obj,e) => { 
     //only when left mousebutton is pressed 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      //update the location 
      mouseLocation = e.Location; 
      //invalidate the control 
      this.Invalidate(); 
     } 
    }; 
} 

protected override void OnPaint(PaintEventArgs pe) 
{ 
    // Call the OnPaint method of the base class. 
    base.OnPaint(pe); 

    // Declare and instantiate a new pen. 
    Pen pen = new Pen(Color.Fuchsia, 15); 
    SolidBrush myBrush = new System.Drawing.SolidBrush(Color.HotPink); 
    // Draw an aqua rectangle in the rectangle represented by the control. 
    Rectangle blublublu = new Rectangle(mouseLocation, this.Size - new Size(25, 25)); 
     pe.Graphics.DrawRectangle(pen, blublublu); 
    pe.Graphics.FillRectangle(myBrush, blublublu); 
} 

protected override void OnMouseMove(MouseEventArgs e) 
{ 
    //nothing here 
} 

Обратите внимание, что я добавил this.SetStyle(...) в конструкторе, так как это позволит предотвратить мерцание при перемещении прямоугольника. Также я изменил this.Location на mouseLocation в методе OnPaint.

Смежные вопросы