Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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. According to the code pictureboxes are created are named as PointA...PointZ

like image 513
Farid-ur-Rahman Avatar asked Jan 18 '23 05:01

Farid-ur-Rahman


2 Answers

In your click handler, cast the 'sender' parameter to a PictureBox and examine its Location.

void pb_point_Click(object sender, EventArgs e)
{
    var pictureBox = (PictureBox)sender;
    MessageBox.Show(pictureBox.Location.ToString());
}
like image 141
Marty Avatar answered Jan 25 '23 16:01

Marty


Sender is your picturebox. 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.
}
like image 20
alexn Avatar answered Jan 25 '23 17:01

alexn