Simulating button click

closet geek

Newcomer
Joined
Apr 2, 2006
Messages
21
How do you simulate a button being clicked by the user in C# or J#?

I have a button called "Button1" and it performs a task when the user clicks on it. How do I then say "pretend the user has clicked Button1" from a different method so that the actions of Button1 can be invoked by the software.

So simple I imagine but I can't spot it.
 
Assuming this is for Windows (not web), you can call the PerformClick() method on the button (Button1.PerformClick()).

Normally that would be considered bad practice unless you're writing some kind of automated test software that has to record button clicks and simulate them. Most would prefer that the Click event call a method. Then where you want to call PerformClick you'd just call that function. For example:
C#:
public class Class1
{
    protected void btnSave_Click(...)
    {
        Save();
    }

    private void OtherFunction()
    {
        // Some other code
        ...
        // Code where you want to call the Click event:
        Save();
    }

    private void Save()
    {
        // Do something
    }
}

-ner
 
Back
Top