Sunday, August 2, 2009

How do you use keypress comands in visual basic?

I have worked with command click buttons but I don't know how to execute the lines of code in my command subscipts by pressing a key board button or how to set the key you need to press. I know very little about keypress comands so be specific.

How do you use keypress comands in visual basic?
see there are three Events from the keyboard which can read ASCII Code of the each key


1%26gt; KeyPress (Argument is ASCII)


2%26gt; Key Down


3%26gt; Key Up





Private Sub TextBox1_keyPress(keyAscii as integer)





end sub





When ever you will press any key the ASCII Code will go in.For example the ASCII code of "A" is 65


and 66 for B , 67 for C so on


and 97 for "a" and 98 for "b" and so on and 13 for enter , 32 for space.and for numeric it is 48 for "0" and 49 for "1" and 57 for "9"


suppose for a TextBox If I want to restrict the user not to use the space then I can write like this





private Sub TextBox1_keyPress(keyascii as integer)


if keyascii= 32 then


keyascii=0


end if


end sub


Means whenever in a TextBox , user will press space then It will set keyasii to zero so space won't enter in the text box. Suppose in a RollNo TextBox you want to restrict the alphabets then





private sub RollNoTextBox_keypress(keyascii as integer)


if keyascii%26gt;=65 and keyascii%26lt;=90 then


keyascii=0


end if


if keyascii%26gt;=97 and keyascii%26lt;=122 then


keyascii=0


end if


if keyascii=32 then


keyasii=0


end if


end sub





This code means if a person will enter A-Z or a-z or space(32) then it won't let them enter.


If you wnat to know the Ascii code of any character then simply write this programm





private sub TextBox1_keypress(keyasii as inetger)


msgbox keyAscii


end sub





whatever key u will press it will display the ascii character.


similarly if for uppercase





private sub TextBox1_keyPress(KeyAscii as Inetger)


if (keyAscii%26lt;=97 and keyascii%26gt;=122) then


keyascii=keyascii-32


end if


end sub





Like if anyone will press "a" code is 97


then it will do 97-32=65 and 65 is code for "A"


so all small letters will be changed to uppercase.





May be this helps.


for ascii code u can also see


http://www.december.com/html/spec/ascii....





if required do write for keyUp and key down.


better install MSDN for help.


No comments:

Post a Comment