Search code examples
c#system.drawing

How write event for drawed shape?


I drew a circle using this code:

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // Create pen.
            Pen blackPen = new Pen(Color.Black, 3);
            // Create rectangle for ellipse.
            Rectangle rect = new Rectangle(0, 0, 200, 100);
            // Draw ellipse to screen.
            e.Graphics.DrawEllipse(blackPen, rect);
        }

how can i write a mouse-over or click event for this circle?


Solution

  • you can assign a click event on the rectangle

    public Form1()
            {
                InitializeComponent();
                Rectangle rect = new Rectangle(0, 0, 100, 200);
                Click += Form1_Click;
            }
    //associate this method to Click event Form
         private void Form1_Click(object sender, EventArgs e)
            {
                Rectangle rect = new Rectangle(0, 0, 200, 100);
                Point cursorPos = this.PointToClient(Cursor.Position);
                //you are in rectangle so message display
                if (rect.Contains(cursorPos))
                {                
                    MessageBox.Show("in");
                }
    
            }