2013-02-27 39 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