2011-03-01 107 views
4

我想繪製一個矩形。事情我想要的是顯示用戶矩形鼠標事件。 enter image description hereC#繪製矩形在鼠標事件上

像在圖像中。這是針對C#.net Forms應用程序的。

幫我實現這個目標。任何幫助表示讚賞。

謝謝 勒芒

+0

這是一個橡皮筋選擇矩形嗎?或者你想讓他們在表單上繪製永久形狀輪廓? – 2011-03-01 06:34:52

+0

是的,它是橡皮筋的選擇,而不是一個永久的 – 2011-03-01 06:44:30

回答

5

你能做到這一點的三個步驟:

  • 首先檢查是否按下鼠標
  • 如果是則在鼠標移動事件保持初始化新矩形拖動鼠標時的位置
  • 然後在繪畫事件上繪製矩形。 (它會被上調,幾乎每一個鼠標事件,取決於鼠標的刷新率和DPI)

你可以做財產以後這樣的(在你的Form):

public class Form1 
{ 

     Rectangle mRect; 

    public Form1() 
    { 
        InitializeComponents(); 

        //Improves prformance and reduces flickering 
     this.DoubleBuffered = true; 
    } 

      //Initiate rectangle with mouse down event 
    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     mRect = new Rectangle(e.X, e.Y, 0, 0); 
     this.Invalidate(); 
    } 

      //check if mouse is down and being draged, then draw rectangle 
    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     if(e.Button == MouseButtons.Left) 
     { 
      mRect = new Rectangle(mRect.Left, mRect.Top, e.X - mRect.Left, e.Y - mRect.Top); 
      this.Invalidate(); 
     } 
    } 

      //draw the rectangle on paint event 
    protected override void OnPaint(PaintEventArgs e) 
    { 
       //Draw a rectangle with 2pixel wide line 
     using(Pen pen = new Pen(Color.Red, 2)) 
     { 
     e.Graphics.DrawRectangle(pen, mRect); 
     } 

    } 
} 

後,如果您想檢查按鈕(如圖所示)是矩形或不是,你可以通過檢查Button的區域來檢查它們是否位於你繪製的矩形中。

+0

嗨,這個作品完美,在pictureBox控件事件上試過同樣的東西,但它沒有奏效。我做錯什麼了嗎? – 2011-03-01 08:35:11

+0

它正在工作,但可能它是在picturebox(在窗體上)下繪製的..向我展示你嘗試的代碼..也檢查@hans Passant的答案..他的技巧將在每一個地方工作。 – 2011-03-01 08:39:11

+1

現在確定它的工作,在我的情況this.Invalidate();應該是pictureBox1.Invalidate();非常感謝你:) – 2011-03-01 08:42:09

2

那些藍色矩形看起來很像控件。在Winforms中很難做到在控件上繪製一條線。您必須創建一個覆蓋設計圖面的透明窗口,並在該窗口上繪製矩形。這也是Winforms設計器的工作方式。示例代碼is here

+0

+1好用的技巧..如果你還記得我自己的回答是來自你在MSDN上的回答之一,雖然它在這種情況下不起作用。 – 2011-03-01 06:50:57

3

通過Shekhar_Pro解決方案繪製一個矩形只是在一個方向(從上到下,從左到右),如果你想畫一個矩形,無論鼠標位置和移動解決方案的方向:

Point selPoint; 
Rectangle mRect; 
void OnMouseDown(object sender, MouseEventArgs e) 
{ 
    selPoint = e.Location; 
    // add it to AutoScrollPosition if your control is scrollable 
} 
void OnMouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     Point p = e.Location; 
     int x = Math.Min(selPoint.X, p.X) 
     int y = Math.Min(selPoint.Y, p.Y) 
     int w = Math.Abs(p.X - selPoint.X); 
     int h = Math.Abs(p.Y - selPoint.Y); 
     mRect = new Rectangle(x, y, w, h); 
     this.Invalidate(); 
    } 
} 
void OnPaint(object sender, PaintEventArgs e) 
{ 
    e.Graphics.DrawRectangle(Pens.Blue, mRect); 
}