Bruno Klein
Bruno Klein

Reputation: 3367

Add event for PictureBox mouse down

I want to make this event to work:

private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    //code
}

I know I have to add an event for this to work but I wasn't able to find the syntax anywhere. How can I add this event?

Upvotes: 2

Views: 8139

Answers (1)

Bojan Komazec
Bojan Komazec

Reputation: 9536

You have to assign event handler to the event, usually in the form's constructor:

class MyForm 
{ 
    PictureBox pictureBox1;

    public MyForm()
    {
        ...
        InitializeComponent(); 
        ...
        pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown);
        ... 
    }
}

If you added your control through Form Designer in Visual Studio, it will automatically generate InitializeComponent() method which creates controls (calls their constructors) so make sure you're accessing controls after the call to InitializeComponent().

You can also assign event handler to the event through Form Designer: select control, right click it, select Properties, click on flash icon (Events), find desired event (MouseDown) and double click it - event handler method will be assigned to that event (you can check the code in InitializeComponent()). Now you just have to write the code in the body of the event handler.

Upvotes: 7

Related Questions