【问题标题】:Get access to the Sender control - C#获取对发件人控件的访问权限 - C#
【发布时间】:2011-11-21 19:13:45
【问题描述】:

如何访问发件人控件(即:更改位置等)?我在运行时在面板中创建了一些图片框,将其单击事件设置为一个函数。我想获取用户单击的图片框的位置。我也试过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 由循环调用以创建提供 X、Y 和点编号的图片框数量。 根据代码创建的图片框命名为PointA...PointZ

【问题讨论】:

    标签: c# winforms dynamic


    【解决方案1】:

    在您的点击处理程序中,将 '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.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-16
        • 2019-12-14
        • 1970-01-01
        相关资源
        最近更新 更多