簡體   English   中英

訪問Sender控件 - C#

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

如何訪問發件人控件(即:更改位置等)? 我在面板的運行時創建了一些圖片框,將其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命名為PointA...PointZ

在您的單擊處理程序中,將'sender'參數強制轉換為PictureBox並檢查其Location。

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

Sender是你的圖片框。 剛剛施展它:

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