2013-06-05 104 views
2

我有一個自定義的按鈕類,當我觸發我的任何自定義按鈕PerformClick時,什麼都不會發生。這是代碼:PerformClick自定義按鈕將不起作用

我的自定義類

public class NonFocusButton : Button 
{ 
    public NonFocusButton() 
    { 
     SetStyle(ControlStyles.Selectable, false); 
    } 
} 

List<NonFocusButton> buttons = new List<NonFocusButton>(); 

聲明這是p功能:

void p() 
{ 
    for (int i = 1; i <= 5; i++) 
    { 
     NonFocusButton aux = new NonFocusButton(); 
     aux.Font = new System.Drawing.Font("Britannic Bold", 15.75F,  
     System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 
      ((byte)(0))); 
     aux.Size = new System.Drawing.Size(192, 43); 
     aux.UseVisualStyleBackColor = true; 
     aux.UseWaitCursor = false; 
     aux.Visible = false; 
     buttons.Add(aux); 
     this.Controls.Add(aux); 
    }    

    // button start 

    buttons[0].Location = new System.Drawing.Point(410, 168); 
    buttons[0].Text = "START GAME"; 
    buttons[0].Click += new System.EventHandler(this.button0_Click); 
} 

private void button0_Click(object sender, EventArgs e) 
{ 
    this.Close(); 
} 

buttons[0].PerformClick(); // will not work 
+1

顯示更多完整的代碼。這裏沒有足夠的上下文來找出問題出在哪裏...... –

回答

2

如何按鈕申報和填寫?這是我的方式,它的工作原理。

// declaration 
List<Button> butons = new List<Button>(); 

// calling 
buttons.Add(new Button()); 
p(); 
buttons[0].PerformClick(); 

編輯:

按鈕已獲得焦點,可以單擊它之前。
爲什麼不這樣做:

button0_Click(buttons[0], EventArgs.Empty); 

或只調用隨時隨地可以調用PerformClick()Close()

+0

我必須對我創建的每個按鈕執行一次點擊,並希望PerformClick可能有效。 –

0

ButtonPerformClick源代碼是:

public void PerformClick() { 
    if (CanSelect) { 
     bool validatedControlAllowsFocusChange; 
     bool validate = ValidateActiveControl(out validatedControlAllowsFocusChange); 
     if (!ValidationCancelled && (validate || validatedControlAllowsFocusChange)) 
     { 
      //Paint in raised state... 
      // 
      ResetFlagsandPaint(); 
      OnClick(EventArgs.Empty); 
     } 
    } 
} 

而且CanSelect

public bool CanSelect { 
    // We implement this to allow only AxHost to override canSelectCore, but still 
    // expose the method publicly 
    // 
    get { 
     return CanSelectCore(); 
    } 
} 

internal virtual bool CanSelectCore() { 
    if ((controlStyle & ControlStyles.Selectable) != ControlStyles.Selectable) { 
     return false; 
    } 

    for (Control ctl = this; ctl != null; ctl = ctl.parent) { 
     if (!ctl.Enabled || !ctl.Visible) { 
      return false; 
     } 
    } 

    return true; 
} 

我作爲到限制的猜測是Selectable標誌來代替添加另一控制標誌如AllowsPerformClick

而不是使用PerformClick,你可以使用反射,例如,

MethodInfo methodOnClick = typeof(Button).GetMethod("OnClick", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); 

// and then... 

methodOnClick.Invoke(myButton, new Object[] { EventArgs.Empty });