如何在PictureBox上捕获鼠标坐标?

我是c#的新手。 我在图片框上有一个图像,我想在图像上绘制一个矩形来捕捉我将绘制的矩形的X,Y坐标和宽度/高度(对照图片框上的图像)。 我知道我必须在pictureBox1_MouseEnter..etc上做点什么。 但我不知道从哪里开始。

private void pictureBox1_MouseEnter(object sender, EventArgs e) { Rectangle Rect = RectangleToScreen(this.ClientRectangle); } 

如果有人能给我示例代码,我将不胜感激。

谢谢。

您根本不想使用MouseEnter 。 您想使用MouseDown ,因为您不希望在用户单击鼠标按钮之后开始跟踪用户绘制的矩形。

因此,在MouseDown事件处理程序方法中,保存游标的当前坐标。 这是矩形的起始位置,点(X,Y)。

 private Point initialMousePos; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { this.initialMousePos = e.Location; } 

然后,在用户停止拖动并释放鼠标按钮时引发的MouseUp事件中 ,您希望保存鼠标光标的最终结束点,并将其与初始起点组合以构建矩形。 构建这样一个矩形的最简单方法是使用Rectangle类的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事件以获取鼠标的当前位置,然后调用Invalidate方法,这将引发Paint事件 。 您的所有绘制代码​​都应该在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语句中包装了一个Pen对象 (我们用来做实际绘图)的usingIDisposable创建实现IDisposable接口的对象(例如画笔和笔)时,这都是很好的通用做法,以防止应用程序中的内存泄漏。

此外, PaintEventArgs为我们提供了Graphics类的实例,它封装了.NET应用程序中的所有基本绘图function。 您所要做的就是在该类实例上调用DrawRectangleDrawImage等方法,将相应的对象作为参数传入,并自动为您完成所有绘图。 很简单吧?

最后,请注意我们在这里完成了同样的事情来创建一个矩形,就像我们最终在MouseUp事件处理程序方法中所做的那样。 这是有道理的,因为我们只想在用户创建矩形时获得矩形的瞬时大小。

我希望这可以帮助你:

http://www.farooqazam.net/draw-a-rectangle-in-c-sharp-using-mouse/

看这里: 如何在Windows窗体PictureBox中选择一个区域?