编程语言
首页 > 编程语言> > 如何检测鼠标是否在winform应用程序中的c#中单击某个形状?

如何检测鼠标是否在winform应用程序中的c#中单击某个形状?

作者:互联网

假设我有一个win form应用程序,我有一个名为pictureBox1的图片框.然后我运行以下代码:

public System.Drawing.Graphics graphics;
public System.Drawing.Pen blackPen = new System.Drawing.Pen(Color.Black, 2);

public void drawVennDiagram()
{
    graphics = pictureBox1.CreateGraphics();
    graphics.DrawEllipse(blackPen, 0, 0, 100, 100);
    graphics.DrawEllipse(blackPen, 55, 0, 100, 100);
}

如果我调用drawVennDiagram(),它将在pictureBox1中绘制两个圆圈,圆圈重叠得足以看起来像一个维恩图.

我想要实现的目标如下:

  • Run Method A if the mouse clicks anywhere outside of the venn diagram but in the picturebox.

  • Run Method B if the mouse clicks only inside of the first circle.

  • Run Method C if the mouse clicks inside of both circles.

  • Run Method D if the mouse clicks only inside of the second circle.

到目前为止,我已经编写了下面的代码,它实际上跟踪了光标点击的位置,但我无法确定光标位置跟随哪个参数(a,b,c,d).

private void pictureBox1_Click(object sender, EventArgs e)
{
    this.Cursor = new Cursor(Cursor.Current.Handle);
    int xCoordinate = Cursor.Position.X;
    int yCoordinate = Cursor.Position.Y;
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    int xCoordinate = e.X;
    int yCoordinate = e.Y;
}

实现这一目标的最佳方法是什么?

解决方法:

是.给定圆以中心(xc,yc)和半径r定位,如果:(x-xc)2(y-yc)2≤r2,则坐标(x,y)在圆内.

鉴于我们知道,我们也知道你的圆圈的中心位于(50,50)和(105,50),每个圆的半径为50.所以现在我们定义一个方法:

public static bool InsideCircle (int xc, int yc, int r, int x, int y) {
    int dx = xc-x;
    int dy = yc-y;
    return dx*dx+dy*dy <= r*r;
}

现在你可以使用:

private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
    int x = e.X;
    int y = e.Y;
    bool inA = InsideCircle(50,50,50,x,y);
    bool inB = InsideCircle(105,50,50,x,y);
    if(inA && inB) {
        C();
    } else if(inA) {
        B();
    } else if(inB) {
        D();
    } else {
        A();
    }
}

但请注意,目前,您绘制的两个圆圈无论如何都不会重叠.

标签:c,net,winforms,picturebox
来源: https://codeday.me/bug/20190717/1488522.html