[英]How to get the name of a control under the mouse pointer ( without making an event handler for each control ) ?
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.我有一个 mdichild 和一个用于拖放的事件处理程序,因此当我在表单中放置一个图像文件时,会使用该图像创建一个图片框 (name = dpic)。
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.我有另一个用于 dpic_Click 的事件处理程序,因此当我单击图像时,我的表单文本就是该图像的名称。
After the first time I drop an image, another dpic is created, because you can't have two cotrols with the same name.在我第一次放置图像后,会创建另一个 dpic,因为您不能有两个具有相同名称的控件。 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. C# 自动更改名称,这使我的事件处理程序仅适用于我放入的最后一张图像。我想如果我可以为我的 mdichild 创建一个事件处理程序,它可以获取鼠标指针下的控件名称,我可以简单地更改返回我指向的图像。
UPDATE更新
Here is my code, I made an event handler for droping in my mdichild:这是我的代码,我为放入我的 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编辑:你把它放在 pic_Click 事件中
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.