2017-07-16 58 views
2

下面的代碼允許我將鼠標懸停在按鈕上的圖像上,但需要重複加載代碼。我想知道是否有一種方法可以縮短並允許使用同一段代碼,但使用不同的按鈕名稱。C#縮短重複代碼的更好方法

我知道private void *NAME*可以是相同的,由不同的按鈕使用,並允許我縮短以下,但隨後讓我懸停在所有的按鈕一次,而不是單獨的懸停。

private void button1_Leave(object sender, EventArgs e) 
    { 
     this.button1.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    private void btnfb_Leave(object sender, EventArgs e) 
    { 
     this.btnfb.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    void btnfb_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.btnfb.BackgroundImage = ((Image)(Properties.Resources.hover_img)); 
    } 

    private void btndiscord_Leave(object sender, EventArgs e) 
    { 
     this.btndiscord.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    void btndiscord_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.btndiscord.BackgroundImage = ((Image)(Properties.Resources.hover_img)); 
    } 

    private void btn_pp_Leave(object sender, EventArgs e) 
    { 
     this.btn_pp.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    void btn_pp_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.btn_pp.BackgroundImage = ((Image)(Properties.Resources.hover_img)); 
    } 

    private void btnhelp_Leave(object sender, EventArgs e) 
    { 
     this.btnhelp.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    void btnhelp_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.btnhelp.BackgroundImage = ((Image)(Properties.Resources.hover_img)); 
    } 

    private void btnsave_Leave(object sender, EventArgs e) 
    { 
     this.btnsave.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 

    void btnsave_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.btnsave.BackgroundImage = ((Image)(Properties.Resources.hover_img)); 
    } 

    private void btnmini_Leave(object sender, EventArgs e) 
    { 
     this.btnmini.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
    } 
+0

使用create abother常見的處理程序C#'委託' – AminM

回答

6

您可以連接你所有的事件相同的處理器...

private void MyButtonLeaveHandler(object sender, EventArgs e) 
{ 
Button button = sender as Button; 
if (button != null) 
{ 
    button.BackgroundImage = ((Image)(Properties.Resources.leave_img)); 
} 
} 

this.button1.Leave += MyButtonLeaveHandler; 
this.btnfb.Leave += MyButtonLeaveHandler; 

同樣可以爲MouseLeave事件

+0

但是,不會說只有設置button1的背景才能具有leav只有e_img?因爲它也需要在不同的時間在btn_pp等。 –

+0

使用你的例子,狀態'你的代碼'在哪裏,我怎麼能得到它來檢測哪個按鈕被懸停?因爲我只想要懸停的按鈕來設置圖像。 –

+0

謝謝。我現在就試試這個。 –