如何检测Windows窗体中的一行单击 [英] How do I detect click on a line in Windows Forms
问题描述
我有一个winforms应用程序
I have a winforms application
这是我的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
Graphics gr;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
gr = this.CreateGraphics();
MyLine myline = new MyLine();
myline.P1 = new Point(100, 0);
myline.P2 = new Point(200, 80);
gr.DrawLine(new Pen(Color.Red), myline.P1,myline.P2);
Rectangle r = new Rectangle(0, 0, 50, 50);
gr.DrawRectangle(new Pen(Color.Teal, 5), r);
if (r.Contains(0,25)) MessageBox.Show("within");
}
private void btnClear_Click(object sender, EventArgs e)
{
gr.Clear(this.BackColor);
}
}
}
class MyLine
{
public Point P1 {get; set;}
public Point P2 { get; set; }
}
我的问题是这个。.
我可以绘制一个矩形,然后查看其中是否有一个点。
I can draw a rectangle, and I can see whether a point is within it.
因此,我可以将程序扩展为是在矩形上单击表单。矩形具有很好的包含功能。
So I could extend the program to say "yes" when a click on the form is within the rectangle. The Rectangle has a Contains function which is great.
但是我想对Line进行同样的操作。
But I want to do the same for Line.
问题在于,winforms没有Line类。我可以编写自己的Line类,但问题仍然存在..如何查找单击是否落在其上?
The problem, is that winforms has no Line class. I could write my own Line class, but the problem remains.. how to find whether a click landed on it?
我注意到WPF具有这样的类如何识别鼠标单击一行?
I notice that WPF has such a class How do I recognize a mouse click on a line?
但是我正在使用winforms。
But i'm using winforms.
推荐答案
使用 GraphicsPath.IsOutlineVisible
方法,当使用指定的 笔
。您可以设置笔的宽度。
Using GraphicsPath.IsOutlineVisible
method you can determine whether the specified point is under the outline of the path when drawn with the specified Pen
. You can set width of the pen.
因此您可以创建 GraphicsPath
,然后使用 GraphicsPath.AddLine
到路径,并检查路径是否包含该点。
So you can create a GraphicsPath
and then add a line using GraphicsPath.AddLine
to the path and check if the path contains the point.
示例:
以下方法检查 p
是否在端点 p1的直线上
和 p2
使用指定的宽度。
The below method, checks if the p
is on the line with end points p1
and p2
using the specified width.
您可以使用更宽的宽度来增加公差,或者如果线宽大于1:
You can use wider width to increase the tolerance or if the line is wider than 1:
//using System.Drawing;
//using System.Drawing.Drawing2D;
bool IsOnLine(Point p1, Point p2, Point p, int width = 1)
{
using (var path = new GraphicsPath())
{
using (var pen = new Pen(Brushes.Black, width))
{
path.AddLine(p1, p2);
return path.IsOutlineVisible(p, pen);
}
}
}
这篇关于如何检测Windows窗体中的一行单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!