Adding a mouse click event handler to a PictureBox

I have an image control, and when I click on it, another PictureBox appears in a specific place. Iow it was not added from the toolbar.

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 to add a MouseClick control to this control?

thanks

+4
source share
4 answers

Just add an event handler using the += operator:

 picOneFaceUpA.MouseClick += new MouseEventHandler(your_event_handler); 

Or:

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

The best way in WinForms to sign up for an event is to select your control in the designer, open the Properties window and select the Events tab. Then select any event you want (click, MouseClick, etc.) and double-click on the space bar to the right of the event name. An event handler will be generated and subscribed to the event.


If you want to subscribe to the event manually, add an event handler to the event

 picOneFaceUpA.MouseClick += PicOneFaceUpA_MouseClick; 

Pressing Tab after writing += will generate a 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 do not need additional information about the click event (for example, which button is pressed), use Click instead. It handles left-clicks by default:

 picOneFaceUpA.Click += PicOneFaceUpA_Click; 

And the handler:

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

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

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

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

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

and delete the event

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

The method should be declared something like this:

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

Source: https://habr.com/ru/post/1446956/


All Articles