2011-11-21 29 views
3

如何訪問發件人控件(即:更改位置等)?我在面板的運行時創建了一些圖片框,將它的click事件設置爲一個函數。我想要獲取用戶點擊的圖片框的位置。我也嘗試this.activecontrol,但它不工作,並給出了放置在窗體中的控件的位置。我使用下面的代碼:訪問發件人控件 - C#

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由循環調用創建PictureBoxes這給X,Y和點號的數量。 根據代碼pictureboxes被創建被命名爲PointA...PointZ

回答

5

在您的點擊處理程序中,將'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. 
}