Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i need to know how can i press the button1 by the program i mean inside the program (Programitically) not by pointing the mouse on that button then pressing the left mouse button
look at my program

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace keyPressed
{
    public partial class Form1 : Form
    {
        string str = "hellow";
        public Form1()
        {
            InitializeComponent();
            pp();
        }

        private void pp()
        {
            //I need to call button1_Click from here  
            //without using the mouse ,how could i do that ?
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(str);
        }
    }
}
Posted

Use the Button.PerformClick() method

C#
private void button1_Click(object sender, EventArgs e)
    {
    button2.PerformClick();
    }

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


[edit]Added example - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Espen Harlinn 6-Feb-11 5:10am    
Nice and simple - just PerformClick :)
#realJSOP 6-Feb-11 6:05am    
Proposed as answer.
Olivier Levrey 6-Feb-11 8:48am    
My 5. I agree. PerformClick is cleaner than directly calling the event handler.
fjdiewornncalwe 6-Feb-11 11:09am    
That's why PerformClick is there... +5.
You can call the event handling method, button1_Click, directly:
private void pp()        
{            
//I need to call button1_Click from here              
//without using the mouse ,how could i do that ? 

button1_Click(this, new EventArgs());

}


If you want to simulate a button click you can send a WM_LBUTTONDOWN[^] to the button control.

Regards
Espen Harlinn
 
Share this answer
 
Comments
OriginalGriff 6-Feb-11 4:44am    
That only actions the single method you specify, rather than any methods which are assigned as handlers to the click event. You also don't need to start throwing windows messages around directly: you can use the Button.PerformClick method instead.
Olivier Levrey 6-Feb-11 8:48am    
I agree. PerformClick is cleaner than directly calling the event handler.
fjdiewornncalwe 6-Feb-11 11:09am    
Between your answer and Griff's I have done both in the past. Both work, but if memory serves me correctly, Griff's is the more accepted method of doing this. +5 for showing that this can be done this way too.
Espen Harlinn 6-Feb-11 11:20am    
Thanks Marcus! as you see, I voted 5 for OriginalGriffs answer too :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900