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

10,079

Solution 1

PointToClient method translates cursor coordinates to control-relative coordinates. I.e. if you cursor is at (screenX, screenY) position on the screen it can be at (formX, formY) position relatively to form's top-left corner. We need to call it to bring cursor position into coordinate system used by our rectangle.

Invalidate method makes control to redraw itself. In our case it triggers OnPaint event handler to redraw rectangle with a new border color.

Solution 2

You can assign Click event handler to control whose surface will be used to draw rectangle. Here is a small example: When you click on form inside of rectangle it will be drawn with red border when you click outside it will be drawn with black border.

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();
    }
}
Share:
10,079

Related videos on Youtube

GurdeepS
Author by

GurdeepS

Updated on June 04, 2022

Comments

  • GurdeepS
    GurdeepS almost 2 years

    Imagine I use the .NET graphic classes to draw a rectangle.

    How could I then assign an event so that if the user clicks a certain point, or a certain point range, something happens (a click event handler)?

    I was reading CLR via C# and the event section, and I thought of this scenario from what I had read.

    A code example of this would really improve my understanding of events in C#/.NET.

    Thanks