Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

  • *Experts*
Posted

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:

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...