2012-10-26 32 views
1

我在我的Windows窗體應用程序的多個按鍵,和我想申請一些風格上btnhover這樣如何對所有按鈕適用相同的風格在windows窗體

private void button1_MouseEnter(object sender, EventArgs e) { 
    button1.UseVisualStyleBackColor = false; 
    button1.BackColor = Color.GhostWhite; 
} 
private void button1_MouseLeave(object sender, EventArgs e) { 
    button1.UseVisualStyleBackColor = true; 
} 

我希望把這種風格在一個地方,我希望它自動適用於我的表單中的所有按鈕。我怎麼能這樣做,請幫助我,並提前感謝

回答

1

如果你真的想PU牛逼這在一個地方,並有自動風格的形式,這將是它自己的類:

class ButtonStyledForm : Form 
{ 
    protected override void OnControlAdded(ControlEventArgs e) 
    { 
     base.OnControlAdded(e); 

     if (e.Control.GetType() == typeof(Button)) 
     { 
      e.Control.MouseEnter += button_MouseEnter; 
      e.Control.MouseLeave += button_MouseLeave; 
     } 
    }  

    protected override void OnControlRemoved(ControlEventArgs e) 
    { 
     base.OnControlRemoved(e); 

     if (e.Control.GetType() == typeof(Button)) 
     { 
      e.Control.MouseEnter -= button_MouseEnter; 
      e.Control.MouseLeave -= button_MouseLeave; 
     } 
    } 

    private void button_MouseEnter(object sender, EventArgs e) { 
     var c = (Button)sender; 
     c.UseVisualStyleBackColor = false; 
     c.BackColor = Color.GhostWhite; 
    } 

    private void button_MouseLeave(object sender, EventArgs e) { 
     var c = (Button)sender; 
     c.UseVisualStyleBackColor = true; 
    } 
} 

然後從這個類,而不是繼承Form

0

這不會自動將它應用到新的按鈕,添加到窗體,但它會應用到所有現有的按鈕,因爲我懷疑是什麼你真正想做的事:

partial class MyForm 
{ 
    foreach(var b in this.Controls.OfType<Button>()) 
    { 
     b.MouseEnter += button1_MouseEnter; 
     b.MouseLeave += button1_MouseLeave; 
    } 
} 

注意,你將不得不改變你的事件處理程序使用sender,而不是直接使用button1,如:

private void button1_MouseEnter(object sender, EventArgs e) { 
    var c = (Button)sender; 
    c.UseVisualStyleBackColor = false; 
    c.BackColor = Color.GhostWhite; 
} 

private void button1_MouseLeave(object sender, EventArgs e) { 
    var c = (Button)sender; 
    c.UseVisualStyleBackColor = true; 
}