Arianule
Arianule

Reputation: 9063

Adding a mouse click eventhandler to a PictureBox

I have a picturebox control and upon clicking it another PictureBox appears at a specific location. I.o.w it wasnt added from the toolbox.

PictureBox picOneFaceUpA = new PictureBox();
        picOneFaceUpA.Location = new Point(42, 202);
        picOneFaceUpA.Width = 90;
        picOneFaceUpA.Height = 120;
        picOneFaceUpA.Image = Image.FromFile("../../Resources/" + picFaceUpToBeMoved[0] + ".png");
        Controls.Add(picOneFaceUpA);
        picOneFaceUpA.BringToFront();

How would I add a MouseClick eventhandler to this control?

Thanks

Upvotes: 8

Views: 50454

Answers (4)

Mr_Green
Mr_Green

Reputation: 41852

It seems you know how to add dynamic controls then you should just do

this.picOneFaceUpA.MouseClick += new MouseEventHandler(yourMethodName); //hook

and to remove a event

this.picOneFaceUpA.MouseClick -= yourMethodName;     //unhook

the method should be declared something like this:

private void yourMethodName(object sender, MouseEventArgs e)
{
    //your code here
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Best way in WinForms to subscribe to event - select your control in designer, go to Properties window and select events tab. Then choose any event you want (Click, MouseClick, etc) and double-click on space to the right of event name. Event handler will be generated and subscribed to event.


If you want to subscribe to event manually, then add event handler to event

picOneFaceUpA.MouseClick += PicOneFaceUpA_MouseClick;

Hitting Tab after you write += will generate handler. Or you can write it manually:

void PicOneFaceUpA_MouseClick(object sender, MouseEventArgs e)
{
   // handle click event
   if (e.Button == MouseButtons.Left)
       MessageBox.Show("Left button clicked");
}

BTW if you don't need additional info about click event (e.g. which button was clicked), then use Click event instead. It handles left button clicks by default:

picOneFaceUpA.Click += PicOneFaceUpA_Click;

And handler:

void PicOneFaceUpA_Click(object sender, EventArgs e)
{
   // show another picture box
}

Upvotes: 2

John Koerner
John Koerner

Reputation: 38087

If you type picOneFaceUpA.Click += then hit tab, it will autocomplete for you and implement the event handler:

    private void button2_Click(object sender, EventArgs e)
    {
        PictureBox picOneFaceUpA= new PictureBox();
        picOneFaceUpA.Click += new EventHandler(picOneFaceUpA_Click);
    }

    void picOneFaceUpA_Click(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }

Upvotes: 1

user27414
user27414

Reputation:

Just add an event handler using the += operator:

picOneFaceUpA.MouseClick += new MouseEventHandler(your_event_handler);

Or:

picOneFaceUpA.MouseClick += new MouseEventHandler((o, a) => code here);

Upvotes: 12

Related Questions