2011-11-21 27 views
3

如何访问发件人控件(即:更改位置等)?我在面板的运行时创建了一些图片框,将它的click事件设置为一个函数。我想要获取用户点击的图片框的位置。我也尝试this.activecontrol,但它不工作,并给出了放置在窗体中的控件的位置。我使用下面的代码:访问发件人控件 - C#

void AddPoint(int GraphX, int GraphY,int PointNumber) 
    { 
     string PointNameVar = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; 
     string [] PointNameArr = PointNameVar.Split(','); 

     PictureBox pb_point = new PictureBox(); 
     pb_point.Name = "Point"+PointNameArr[PointNumber]; 

     pb_point.Width = 5; 
     pb_point.Height = 5; 
     pb_point.BorderStyle = BorderStyle.FixedSingle; 
     pb_point.BackColor = Color.DarkBlue; 
     pb_point.Left = GraphX; //X 
     pb_point.Top = GraphY; //Y 
     pb_point.MouseDown += new MouseEventHandler(pb_point_MouseDown); 
     pb_point.MouseUp += new MouseEventHandler(pb_point_MouseUp); 
     pb_point.MouseMove += new MouseEventHandler(pb_point_MouseMove); 
     pb_point.Click += new EventHandler(pb_point_Click); 
     panel1.Controls.Add(pb_point); 
    } 


    void pb_point_Click(object sender, EventArgs e) 
    { 
     MessageBox.Show(this.ActiveControl.Location.ToString()); //Retrun location of another control. 
    } 

功能AddPoint由循环调用创建PictureBoxes这给X,Y和点号的数量。 根据代码pictureboxes被创建被命名为PointA...PointZ

回答

5

在您的点击处理程序中,将'sender'参数强制转换为PictureBox并检查其位置。

void pb_point_Click(object sender, EventArgs e) 
{ 
    var pictureBox = (PictureBox)sender; 
    MessageBox.Show(pictureBox.Location.ToString()); 
} 
2

Sender是你的图片箱。只需投它:

void pb_point_Click(object sender, EventArgs e) 
{ 
    var pictureBox = (PictureBox)sender; 
    MessageBox.Show(pictureBox.Location.ToString()); //Retrun location of another control. 
}