简体   繁体   中英

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

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

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();
    }
}

PointToClient method translates cursor coordinates to control-relative coordinates. Ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM