gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:36:22 26 4
gpt4 key购买 nike

假设我有一个 win 表单应用程序和一个名为 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,y) 在圆内如果:(x-xc)2+(y-yc) 2≤r2

鉴于我们知道这一点,我们也知道您的圆圈的圆心位于 (50,50)(105,50),并且每个圆的半径为 < em>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# - 如何检测鼠标是否在 winform 应用程序的 c# 中单击了某个形状的内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34582234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com