Click here to Skip to main content
15,886,541 members
Please Sign up or sign in to vote.
2.33/5 (4 votes)
See more:
I have a button in form
I want when user press space event's button_click is running
how do this????
tnx
Posted
Comments
Sergey Alexandrovich Kryukov 28-Jun-11 12:58pm    
Tag it! WPF, Forms, ASP.NET, what?!
--SA

Do the following:

Set the form's KeyPreview to true so that the form can capture the Spacebar.

C#
this.KeyPreview = true;

Then use the KeyDown event of the form:
this.KeyDown += new KeyEventHandler(Form1_KeyDown);


Suppose you have a button's event handler like this:
C#
private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button clicked");
        }


Use the button1.PerformClick() in the Form1_KeyDown function:

C#
void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                button1.PerformClick();  // This will call the button1_Click event handler
            }
        }


Should work now.
 
Share this answer
 
Comments
jiji2663 28-Jun-11 15:54pm    
tnx Tarun
Tarun.K.S 29-Jun-11 2:54am    
Glad it helped. :)
Good morning,

Set
this.KeyPreview = true;

on your form's constructor, or simply use the form designer and set the KeyPreview parameter to true.

Then you can use the KeyPress, KeyDown or KeyUp events to handle keyboard input on the form.

Take a look at:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx[^]
 
Share this answer
 
v2
Comments
jiji2663 28-Jun-11 15:55pm    
tnx UJimbo
You have to handle one of the key events, keydown, keyup, keypress. Then, have your click event call a method and call the same method if space is pushed.
 
Share this answer
 
Comments
jiji2663 28-Jun-11 4:21am    
how handle key events
Christian Graus 28-Jun-11 4:39am    
Does google not work where you live ? If you don't know how to hook up an event in the IDE ( I'm assuming this is a windows app, as you did not say ASP.NET ), then you need to read a beginners book before you try to write anything.
forms' onkeypressevent write a javascript function which detectes the key code if it is 32(space bar ascii) then call (selector).click() using jquery.

below link might help you

http://forums.asp.net/t/1219638.aspx/1

Thanks
Faisal
 
Share this answer
 
Comments
Christian Graus 28-Jun-11 4:38am    
How do you know he's writing a web app ? He's not said at all that he is, and the word 'form' implies he is not.

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