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

One*_*tig 3 .net c# picturebox winforms

假设我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

如果我打电话drawVennDiagram(),它将绘制两个圆圈,pictureBox1圆圈重叠到足以看起来像一个维恩图.

我想要实现的目标如下:

  • A如果鼠标单击维恩图外部的任何位置但在图片框中单击,则运行"方法" .

  • B如果鼠标仅在第一个圆圈内部单击,则运行"方法" .

  • C如果鼠标在两个圆圈内部单击,则运行方法.

  • D如果鼠标仅在第二个圆圈内部单击,则运行"方法" .

到目前为止,我已经编写了下面的代码,它实际上跟踪了光标点击的位置,但我无法确定光标位置跟随哪个参数(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;
}
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*sem 5

是.给定的圆被定位成与中心(X Ç,Y Ç)和半径- [R ,坐标(X,Y)是在圆内,如果:(XX Ç)2 +(Y-Y c ^)2 ≤R 2.

鉴于我们知道,我们也知道你的圆圈的中心位于(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;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以使用:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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