c# 如何只在特定位置触发点击

标签 c# winforms

我有一个 C# UserControl。在其中我重写了 OnPaint 方法。然后我在里面画了一个圆圈。

Bitmap GraphicsImage = new Bitmap(24, 24, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics.FromImage(GraphicsImage).Clear(btnColor);

Graphics graphics = e.Graphics;
SolidBrush myBrush = new SolidBrush(btnColor);
Pen myPen = new Pen(btnColor);
// Draw the button in the form of a circle
graphics.DrawEllipse(myPen, 0, 0, 40, 40);
graphics.FillEllipse(myBrush, new Rectangle(0, 0, 40, 40));

这是图片

enter image description here

我想要的是只有当鼠标在圆圈内时才触发鼠标点击事件,因为用户控件更大。

最佳答案

可以在用户控件上触发所有点击事件,判断鼠标位置是否在圆圈内

private void yourcontrol_Click(object sender, EventArgs e)
{
    Point pt = yourcontrol.PointToClient(System.Windows.Forms.Control.MousePosition);
    //check if point is in the circle with 
    if (Math.Sqrt(Math.Pow(pt.X - xCenterOfCircle, 2) + Math.Pow(pt.Y - yCenterOfCOircle, 2)) < radius)
    {
      //do something   
    }
}

xCenterOfCircle 必须是圆心的 x 位置,yCenterOfCircle 必须是 y 位置。我假设在您的示例中它是控件的中心,半径将是控件大小的一半。

关于c# 如何只在特定位置触发点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36339523/

相关文章:

c# - 如何加入收到的多部分短信(GSM 调制解调器)(C#)

c# - MaskedTextBox 的多行掩码

c# - 列出网络中所有可用的服务器

c# - DrawString自定义控件文本在winforms C#中不显示

c# - 程序崩溃后运行清理

c# - 如何递归地将 IEnumerable<T> 转换为字符串?

c# - 如何翻译新对象的创建?

C#多线程问题

c# - WinForms 中的数据绑定(bind)执行异步数据导入

c# - 类foo可以设计,但不是文件错误中的第一个类