binding a key to a button

renjivraman

Member
Joined
Sep 9, 2006
Messages
23
Location
India
Programming Experience
1-3
hi all,i would love to know how can we bind a keyboard button (eg:delete) to a button in my form,so that when i press delete button on my keyboard it should execute the code i written in click event of the button in my form...
 
There's no binding involved. You handle the KeyDown or KeyPress event of your form, test for the relevant key and, if found, call the PerformClick method of the Button. Make sure the form's KeyPreview property is set to True.
 
dear JM, i tried it on an mdi application and found that it is workin on the mdi parent but not on any of the child forms..can u pls tell me why is it so..and a way to achieve it on mdi applications...regards
 
Let me guess. You haven't set the child form's KeyPreview property to True like I specifically said to do in my previous post. That's the only reason I can think of that it wouldn't work because it works fine for me.
 
hi JM u ROcks ..i have got it ....it wasnt coz of "keypreview property"it happened coz i wrote some "bad code"..which always kept the focus on to the datagrid i have on the child form durin form load...anyway now i would love to know one more thing ,iam designing an application for a marketing firm..now the thing is that my clientwant me to allocate some standard keys for the entire application..(eg:d for DELETE btn,u for UPDATE btn etc.) coz they will b using keyboard most often..now i dont know how to keep a single key standardized for the entire application (that means if i press d it should call the deletebtn click event on the form that is presently active..ofcourse if it contain a delete button)i hope u can suggest me a professional way to achieve it ...thanking u again....
 
There's no easier way than what you're already doing. You will have to implement the same thing for each form that requires it. There are various ways you could vary it but I don't really se an easier way. If the buttons are relatively consistent then you can implement it on a base class and have the other forms inherit that, but if the button combinations are many then thta's not really an option. You could define a class that knows all the keyboard shortcuts and searches a form for the corresponding button, then have each form create an instance of that class and pass it a reference to itself from the KeyDown event handler. Similarly you could have a method in a module that did the same thing when passed a Keys value and a form reference.
 
Back
Top