0

i have PictureBox, how can I draw a shape/line that fires on MouseEnter event and change color or do more.

private void ImgViewer_Paint(object sender, PaintEventArgs e)
        {
            var graph = e.Graphics;
            using (var pen = new Pen(Color.FromArgb(0, 255, 0)))
                graph.DrawLine(pen, x1, y1, x2, y2);
        }

this code is not enough, i guess

Imp0ssible
  • 49
  • 2
  • 8
  • Take a look at this topic: [Draw an arrow on a picturebox in c#](http://stackoverflow.com/questions/4255614/draw-an-arrow-on-a-picturebox-in-c-sharp) – Jordy van Eijk Mar 11 '13 at 13:37
  • Which one do you have problem with? Drawing on `MouseEnter`? Following the mouse pointer? Or changing color? – Mohammad Dehghan Mar 11 '13 at 13:42
  • I need, that line(s) fires on MouseEnter or Click not the PictureBox itself. Tnx – Imp0ssible Mar 11 '13 at 13:42
  • 1
    Some answer I found here http://stackoverflow.com/questions/10768570/graphic-drawline-draw-line-and-move-it?answertab=active#tab-top – Imp0ssible Mar 11 '13 at 14:39

1 Answers1

0

If you know the equation of the shape you could calculate whether the mouse is within or outside the shape area. Note that this is easy if the shape is consisted of the straight lines or circles (ellipses) for which the geometrical equations are relatively simple. For instance if your shape is a triangle with x and y coordinates (10,10), (50,10) and (30,50) than you should derive the equations of the lines using the equation of the line in two points:

y-y1 = ((y2-y1)/(x2-x1))*(x-x1)

the equations of the lines of our triangle would be:

y=1
y=2*x-10
y=-2*x+110

We should draw that triangle on some canvas, let's say on the PictureBox with FixedSingle border. Add the Paint event handler

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
     Point[] p = new Point[3];
     p[0] = new Point(10,10);
     p[1] = new Point(50,10);
     p[2] = new Point(30,50);
     e.Graphics.DrawLines(Pens.Black, p);
     e.Graphics.FillPolygon(Brushes.Red, p);
}

Triangle

We should add the MouseMove event handler for the PictureBox

bool inside = false;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
     if (e.Y > 10 && e.Y < 2 * e.X - 10 && e.Y < -2 * e.X + 110)
     {
          if (!inside)
          {
               inside = true;
               HandleMouseEnter();
          }
     }
     else
          inside = false;
 }
 void HandleMouseEnter()
 {
       MessageBox.Show("Mouse inside");
 }

In if statement whether the mouse cursor is within the triangle (note that the coordinate origin in C# is on the top-left corner but it is similar to the real geometry). The HandleMouseEnter is the method that handles the mouse enter.

You could use similar approach for an arbitrary shape but you should have geometry equations that describe it.

Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33