PerformClick on custom按钮不起作用

时间:2013-06-05 22:48:26

标签: c# button

我有一个按钮的自定义类,当我为任何自定义按钮触发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

2 个答案:

答案 0 :(得分:2)

如何声明和填充按钮?这就是我拥有它,它的工作原理。

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

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

修改

按钮必须在点击之前获得焦点 为什么不这样做:

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

或只是在您拨打Close()的任何地方致电PerformClick()

答案 1 :(得分:0)

Button PerformClick源代码为:

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 });