在表单上调用n个按钮的事件

时间:2014-04-25 13:44:45

标签: c# events button

在我的previus帖子中,我问如何创建一组n个可拖动的按钮,这些按钮工作正常,但我现在正在研究以下内容:

我在图像上放置了一个图像,并加载了一个坐标矩阵,这样当我也拖动图像时,按钮“跟随图像”,我试图通过在按钮完成时调用一个事件来完成它被拖动,调用事件并将“图像坐标”转换为“形状坐标”。它只适用于一个,但是当我放置n个按钮时出现问题,因为我不知道如何“识别”哪个按钮称为事件,我将告诉你我是如何做到的:

 int x, y;

 //Creates a set of four buttons with an icon
 for (int i = 0; i < 4; i++)
 {
     x = rnd.Next(1, this.Width - 30);
     y = rnd.Next(1, this.Height - 30);
     botonCustom newboton = new botonCustom(32, 32, new Point(x, y), imageList1);

     //New event for each button (Is it ok to do?)
     //I tried to call the same function newboton_Move, since i do not know how to create an event for each button
     newboton.Move += new EventHandler(newboton_Move);

     //Name the button and writes it on a lablel
     newboton.Description = EtiDiamond[i];
     DiamondButton.Add(newboton);
     this.Controls.Add(newboton);
  }   

这是被调用的函数:

private void newboton_Move(object sender, EventArgs e)
{
   // Here i use the coordinates transform method, i won't place the code because
   // its too big and it goes against the rules :P, i think if i could somehow know which button called this...         
}

感谢您阅读本文

1 个答案:

答案 0 :(得分:4)

sender是引发事件的按钮

var myButton = sender as Button;