How do I programmatically invoke an event?

10,499

Solution 1

You might consider changing your design: at least move the logic from button1_Click handler somewhere else so that you'll be able to invoke it from wherever you want.

Solution 2

You can do something like this:

    private void button1_Click(object sender, EventArgs e)
    {
        OnButtonClick();
    }

    private void OnButtonClick()
    {

    }

Then you can call your OnButtonClick() wherever you need to.

Solution 3

The Control class, from which Button inherits, has the OnClick method, which invokes the Click event. Using reflection, you can call this method, even though it is declared protected. For instance, I created the following extension method:

public static void PerformClick(this Control value)
    {
        if (value == null)
            throw new ArgumentNullException();

        var methodInfo = value.GetType().GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
        methodInfo.Invoke(value, new object[] { EventArgs.Empty });
    }

Although, this may be regarded as a dirty hack...

Solution 4

Not exactly the answer you were probably looking for:::

You might just call the code you want to run, move the meat of the code outside the OnClick handling method. The OnClick method could fire that method the same as your code.

Share:
10,499

Related videos on Youtube

hunch_hunch
Author by

hunch_hunch

60% of the time it works, every time.

Updated on April 21, 2022

Comments

  • hunch_hunch
    hunch_hunch about 2 years

    I am creating a C# Windows Mobile application that I need to programmatically invoke the click event on a Button.

    I have looked at the Button class and do not see a way to do this.

  • Dovi
    Dovi about 15 years
    I cannot think of any sane reason why anybody would want to click buttons programatically.