简体   繁体   English

访问Sender控件 - C#

[英]Get access to the Sender control - C#

How do I get access the sender control (ie: changing is location etc)? 如何访问发件人控件(即:更改位置等)? I have created some picture boxes at the runtime in a panel set its click event to a function. 我在面板的运行时创建了一些图片框,将其click事件设置为一个函数。 I want to get the location of the picturebox clicked by the user. 我想获取用户点击的图片框的位置。 I also tried this.activecontrol but its not working and gives the location of a control placed in the form. 我也尝试过this.activecontrol但它没有工作,并给出了窗体中放置的控件的位置。 I am using the following code: 我使用以下代码:

    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.
    }

The function AddPoint is called by a loop to create number of PictureBoxes which give X,Y and Point number. AddPoint函数由循环调用,以创建多个PictureBox,它们给出X,Y和Point编号。 According to the code pictureboxes are created are named as PointA...PointZ 根据代码创建的PointA...PointZ命名为PointA...PointZ

In your click handler, cast the 'sender' parameter to a PictureBox and examine its Location. 在您的单击处理程序中,将'sender'参数强制转换为PictureBox并检查其Location。

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

Sender is your picturebox. Sender是你的图片框。 Just cast it: 刚刚施展它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM