C#缩短重复代码的更好方法

时间:2017-07-16 18:40:25

标签: c# winforms

以下代码允许我将鼠标悬停在按钮上的图像上,但需要重复加载代码。我想知道是否有一种方法可以缩短并允许使用相同的代码但使用不同的按钮名称。

我知道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));
    }

1 个答案:

答案 0 :(得分:6)

您可以将所有活动连接到同一个处理程序......

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

MouseLeave

同样,您可以为{{1}}事件

创建另一个常用处理程序