你不想使用MouseEnter
可言。您想使用MouseDown
,因爲您不想開始跟蹤用戶繪製的矩形,直到他們單擊鼠標按鈕。
所以在MouseDown
事件處理函數方法中,保存遊標的當前座標。這是矩形的起始位置,點(X,Y)。
private Point initialMousePos;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.initialMousePos = e.Location;
}
,然後在MouseUp
event,當用戶停止拖動並釋放鼠標按鍵被提出,要保存鼠標光標的最後終點,並結合起來,與最初的出發點建立一個矩形。建立這樣一個矩形的最簡單方法是使用Rectangle
class的FromLTRB
靜態方法:
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Save the final position of the mouse
Point finalMousePos = e.Location;
// Create the rectangle from the two points
Rectangle drawnRect = Rectangle.FromLTRB(
this.initialMousePos.X,
this.initialMousePos.Y,
finalMousePos.X,
finalMousePos.Y);
// Do whatever you want with the rectangle here
// ...
}
你可能想在MouseMove
事件處理方法與一些繪畫代碼此相結合,給用戶一個視覺指示他們在繪製時繪製的矩形。
的權方式做,這是處理MouseMove
event得到鼠標的當前位置,然後調用Invalidate
方法,這將提高Paint
event。您的所有繪畫代碼應該位於Paint
事件處理程序中。這是比你在網上找到的很多樣本更好的方法,你會在MouseMove
事件處理程序方法中看到類似CreateGraphics
的內容。如果可能,避免這種情況。
樣品實施:
private Point currentMousePos;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
// Save the current position of the mouse
currentMousePos = e.Location;
// Force the picture box to be repainted
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// Create a pen object that we'll use to draw
// (change these parameters to make it any color and size you want)
using (Pen p = new Pen(Color.Blue, 3.0F))
{
// Create a rectangle with the initial cursor location as the upper-left
// point, and the current cursor location as the bottom-right point
Rectangle currentRect = Rectangle.FromLTRB(
this.initialMousePos.X,
this.initialMousePos.Y,
currentMousePos.X,
currentMousePos.Y);
// Draw the rectangle
e.Graphics.DrawRectangle(p, currentRect);
}
}
幾件事情需要注意這個代碼,如果你從來沒有做過任何類型的畫前。第一件事是我在using
statement中包裝了Pen
object(我們用來做實際製圖)的創建。每當您創建一個實現IDisposable
interface的對象(如畫筆和筆)以防止應用程序中發生內存泄漏時,這是很好的一般練習。
此外,PaintEventArgs
爲我們提供了一個Graphics
class的實例,它將所有基本繪圖功能封裝在.NET應用程序中。所有你所要做的就是調用的方法,如對類實例DrawRectangle
或DrawImage
,通過在適當的對象作爲參數,而所有的圖紙被自動完成的。很簡單,對嗎?
最後,請注意,我們所做的正是這裏同樣的事情來創建一個矩形,因爲我們在MouseUp
事件處理方法,最終做到。這很有意義,因爲我們只是想在用戶創建矩形時獲得矩形的即時大小。
感謝科迪,你的代碼工作正常,你介意給我快速繪畫樣本? – Kelly 2011-05-22 10:46:17
@Kelly:用繪畫樣本更新。不知道你在.NET世界中對這種類型的事物有多熟悉,所以我試圖儘可能地解釋它。如果您有任何問題,請留下評論! – 2011-05-22 10:58:18