How to get the name of a control under the mouse pointer ( without making an event handler for each control ) ?

StackOverflow https://stackoverflow.com/questions/5846141

  •  27-10-2019
  •  | 
  •  

سؤال

I have an mdichild, and an eventhandler for draganddrop so when I drop an image file in my form, a picturebox ( name = dpic ) is created with that image.

I have another eventhandler which is for dpic_Click, so when I click on the image, my form's text is the name of that image.

After the first time I drop an image, another dpic is created, because you can't have two cotrols with the same name. C# automatically changes the name and that makes my event handlers only work for the last image I dropped in. I think if I could make an event handler for my mdichild that gets the name of the control that is under the mouse pointer I could simply change back the image I am pointing at.

UPDATE

Here is my code , I made an event handler for droping in my mdichild :

void mdiChild_DragDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {                
            dpic = new PictureBox() ;
            string[] filepath = (string[])e.Data.GetData(DataFormats.FileDrop);
            Image image = Image.FromFile(filepath[0]);
            dpic.Image = image;
            dpic.Tag = Path.GetFileName(filepath[0]);                
            this.ActiveMdiChild.Controls.Add(dpic);
            dpic.ContextMenuStrip = this.contextMenuStrip1;
            this.ActiveMdiChild.Refresh();
            dpic.BringToFront();
            this.ActiveMdiChild.ActiveControl = dpic;

            dpic.Click += new EventHandler(dpic_Click);  
// _____this helped me do it_________________________________________________
           foreach (Control c in this.ActiveMdiChild.Controls)
            {
                c.Click += new EventHandler(c_Click);
            } 
// ________________________________________________________________________
        } 
    }
هل كانت مفيدة؟

المحلول

What you are looking for is a sender. The sender will tell which image was clicked and will allow you to get its name.

PictureBox picSender = (PictureBox)sender;
label1.Text = picSender.Name;

EDIT : You put that in the pic_Click event

نصائح أخرى

I don't understand exactly what you want to do here, possibly layering new pictureboxes with dropped images on the form?

If that is so you can use a

 List<PictureBox> picboxes = new List<PictureBox>();

and where you do:

 dpic = new PictureBox() ;

change to

PictureBox dpic = new PictureBox() ;
 picboxes.Add(dpic);
 this.Controls.Add(dpic);

But please note that you cannot have unlimited controls declared.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top