2012-04-05 22 views
0

我需要繼承事件和屬性。例如,我需要圍繞表單移動一張圖片。 我有這個代碼移動一張圖片,但我需要創建具有相同行爲的多個圖像。如何繼承對象之間的事件

private void pictureBox_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     x = e.X; 
     y = e.Y; 
    } 
} 

private void pictureBox_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     pictureBox.Left += (e.X -x); 
     pictureBox.Top += (e.Y - y); 
    } 
} 

回答

3

創建自定義控制:

public class MovablePictureBox : PictureBox 
{ 
    private int x; 
    private int y; 

    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     base.OnMouseDown(e); 

     if (e.Button == MouseButtons.Left) 
     { 
      x = e.X; 
      y = e.Y; 
     } 
    } 

    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     base.OnMouseMove(e); 

     if (e.Button == MouseButtons.Left) 
     { 
      Left += (e.X - x); 
      Top += (e.Y - y); 
     } 
    } 
} 

UPDATE: 而是附加一個代表,你應該重寫繼承事件的功能,如Microsoft建議here。 創建此控件後,只需編譯程序並從工具箱中拖動MovablePictureBoxes即可形成。它們都是可拖動的(或者可移動的,如果你願意的話)。

+0

謝謝,但是當我想實現自定義控件時,當我對程序框進行編程時,我遇到了一個問題。如何以編程方式爲主類中的每個圖片框使用此自定義控件,謝謝 – marduck19 2012-04-07 18:48:04

+0

@ marduck19,如果要以編程方式創建它們,則只需創建與標準圖片框完全相同的圖片,但使用類名稱MovablePictureBox代替。例如。 'var pictureBox = new MovablePictureBox()' – 2012-04-07 21:22:51

+0

感謝您對朋友的幫助,我對此非常瞭解。來自瓜達拉哈拉墨西哥的問候=) – marduck19 2012-04-08 00:21:57

1

你真正想要做的是有你的多重PictureBoxes共享相同的事件處理程序:

private void pictureBox_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
     // the "sender" of this event will be the picture box who fired this event 
     PictureBox thisBox = sender as PictureBox;    

     thisBox.Left += (e.X -x); 
     thisBox.Top += (e.Y - y); 
    } 
} 

每次你的窗體上創建的PictureBox不斷掛鉤起來的一樣,已經創建,事件。如果你看看上面的代碼,你會注意到它決定了哪個PictureBox調用它並且隻影響那個圖片框。