# How to know if I click on a line in c #

1

Good day. I have a small problem, I'm doing a simple graph editor, drawing 2 `ellipses` and a line that goes to the center of each of those `ellipses` , I need to click on the line it changes color but I do not have idea of how to know when you have clicked on any part of this line, I would greatly appreciate your help:)

``````Pen pen = new Pen(Color.Black);
Graphics g = CreateGraphics();
Nodo n = new Nodo(new Point(100, 100));
Nodo n1 = new Nodo(new Point(200, 200));
Arista a = new Arista(n, n1);//los parametros son nodo origen y nodo destino

g.DrawEllipse(pen, n.centro.X-25, n.centro.Y-25, 50, 50);
g.DrawEllipse(pen, n1.centro.X - 25, n.centro.Y - 25, 50, 50);
g.DrawLine(pen, n.centro, n1.centro);
``````

asked by Arturo García Pérez 05.06.2018 в 05:29
source

2

As @gbianchi says in a comment, the objects that are drawn by `Graphics` are not "clickables", so they do not have a `Click` event to subscribe to.

I will give you a solution using mathematics. The first thing we should know is that the equation of a line is defined with this formula:

y = mx + b

Knowing this, what you must do is store in some variable the two points that define your line. To simplify everything, I will work with integers only.

Following your example, I see that you draw your line from `n.centro` to `n1.centro` , so these are the points that define your line.

Now, what we do is subscribe to the Click event from where you are drawing ( `Form` , `PictureBox` ..). In this example, to the form. In this event, we first calculate the equation of the line given two points, and then we check if the point where it was pressed corresponds to the defined line:

``````private void form1_MouseClick(object sender, MouseEventArgs e)
{
Point p1 = n.centro;
Point p2=n1.centro;

//Calculamos la ecuación de la recta dados dos puntos
int m = (p2.Y - p1.Y) / (p2.X - p1.X);
var b = p1.Y - (m * p1.X);

//Comprobamos el valor de y en la recta para el valor X del punto pulsado
int y = m * e.Location.X + b;

//Si la y está dentro de la línea (con un margen de sensibilidad que decidamos)