How to assign a click event handler to parts of a drawn rectangle?

Imagine using .NET graphics classes to draw a rectangle.

How can I assign an event so that if the user clicks a specific point or a specific range of points, something happens (click event handler)?

I read the CLR through C # and the events section, and I thought of this scenario from what I read.

The sample code for this will really improve my understanding of events in C # /. NET

thanks

+3
source share
2 answers

The PointToClient method translates the coordinates of the cursor into control relative coordinates. That is, if the cursor is at the (screenX, screenY) position on the screen, it can be in the position (formX, formY) relative to the upper left corner. We need to call it to display the cursor position in the coordinate system used by our rectangle.

The invalidate method makes the control redraw. In our case, it runs the OnPaint event handler to redraw the rectangle with the new border color.

0
source

You can designate a Click event handler to control the surface of which will be used to draw the rectangle. Here is a small example: When you click on the shape inside the rectangle, it will be drawn with a red frame; when you click on it, it will be drawn with a black frame.

public partial class Form1 : Form { private Rectangle rect; private Pen pen = Pens.Black; public Form1() { InitializeComponent(); rect = new Rectangle(10, 10, Width - 30, Height - 60); Click += Form1_Click; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.DrawRectangle(pen, rect); } void Form1_Click(object sender, EventArgs e) { Point cursorPos = this.PointToClient(Cursor.Position); if (rect.Contains(cursorPos)) { pen = Pens.Red; } else { pen = Pens.Black; } Invalidate(); } } 
+5
source

All Articles