3

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

2 回答 2

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()

于 2013-06-05T23:41:35.437 回答
1

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.

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

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

// and then...

methodOnClick.Invoke(myButton, new Object[] { EventArgs.Empty });
于 2015-07-17T03:14:44.983 回答