2013-02-27 52 views
1

我有一个关于鼠标事件的简单问题。GDI图形对象上的鼠标OnDrag事件

我有一个WinForms应用程序,我用GDI +图形对象 绘制简单的形状,一个圆。

现在我想要做的就是用鼠标拖动这个形状。

所以当用户移动鼠标时,当左键仍然按下时 我想移动物体。

我的问题是如何检测用户是否仍然按下鼠标左键? 我知道winforms中没有onDrag事件。 有什么想法?

+0

但你有onMouseDown和onMouseUp,对吗? – 2013-02-27 12:05:53

回答

1

查看这个非常简单的例子。它并不包含GDI +绘图的许多方面,但可以让您了解如何在winforms中处理鼠标事件。

using System.Drawing; 
using System.Windows.Forms; 

namespace WindowsFormsExamples 
{ 
    public partial class DragCircle : Form 
    { 


     private bool bDrawCircle; 
     private int circleX; 
     private int circleY; 
     private int circleR = 50; 

     public DragCircle() 
     { 
      InitializeComponent(); 
     } 

     private void InvalidateCircleRect() 
     { 
      this.Invalidate(new Rectangle(circleX, circleY, circleR + 1, circleR + 1)); 
     } 

     private void DragCircle_MouseDown(object sender, MouseEventArgs e) 
     { 
      circleX = e.X; 
      circleY = e.Y; 
      bDrawCircle = true; 
      this.Capture = true; 
      this.InvalidateCircleRect(); 
     } 

     private void DragCircle_MouseUp(object sender, MouseEventArgs e) 
     { 
      bDrawCircle = false; 
      this.Capture = false; 
      this.InvalidateCircleRect(); 
     } 

     private void DragCircle_MouseMove(object sender, MouseEventArgs e) 
     { 

      if (bDrawCircle) 
      { 
       this.InvalidateCircleRect(); //Invalidate region that was occupied by circle before move 
       circleX = e.X; 
       circleY = e.Y; 
       this.InvalidateCircleRect(); //Add to invalidate region the rectangle that circle will occupy after move. 
      } 
     } 

     private void DragCircle_Paint(object sender, PaintEventArgs e) 
     { 
      if (bDrawCircle) 
      { 
       e.Graphics.DrawEllipse(new Pen(Color.Red), circleX, circleY, circleR, circleR); 
      } 
     } 


    } 
} 
+0

感谢您的回答 – Elior 2013-02-27 12:45:00