Search code examples
c#buttonclicksimulate

How to Simulate a mouse/Button Click in c#


I have written a program that amounts to some thousand lines of code and many buttons. I now wish to simulate this code from another Button. I've write a smaller program below to simulate what I want to do. I've looked at other examples it seems as if it would be quite simple to do but HOW!

Button1.PerformClick();

Wont compile, But how to Simulate a button click?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp13
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Some simulation code clcick button 2/3
            //Button1.PerformClick();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button1.Clicked");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button2.Clicked");
        }
    }
}

Solution

  • I think you made a spelling mistake. It should be button3 instead of Button3. The same code worked for me:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button1.Clicked");
        }
    
        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button2.Clicked");
        }
    
        private void button3_Click(object sender, EventArgs e)
        {
            button1.PerformClick();
        }      
    }