访问Sender控件 - C#

时间:2011-11-21 19:13:46

标签: c# winforms dynamic

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

    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来创建多个PictureBox,它们给出X,Y和Point编号。 根据代码,创建的图片框命名为PointA...PointZ

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:2)

Sender是您的图片框。只是施展它:

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