Allow computer keypad form be controlled from keyboard - vb6

I have created a dialer in VB6 to dial a phone number. It has the following buttons: the digits 0-9, backspace, "Call", and "Disconnect". Now I want enter numbers in the form using the keypad part of the keyboard. In the text box, any key can be typed in using the keypad. But I only want the number pad to operate.
For that I checked ASCII values using the KeyPress event - seeing if the pressed key value lies in between 47 and 58. But along with the key values its ASCII values are also getting displayed in the text box.
One more thing - I have one MS Flex Grid on the form along with the dialer. So when the cursor is on the form, or if the mouse is clicked anywhere other than the text box, values don't display in the text box. So how do I always keep focus on the text box?
Dim val As Integer
Private Sub append(val As Integer)
Text1.Text = Text1.Text & val
End Sub
Private Sub Backspace_Click()
With Text1
'FOCUS TO THE TEXTBOX
.SetFocus
'PUT THE CURSOR AT THE END OF THE TEXT
.SelStart = Len(.Text)
'SEND THE KEY
SendKeys ("{BACKSPACE}")
'AND THATS IT :D
End With
End Sub
Private Sub key_0_Click()
val = 0
append val
End Sub
Private Sub key_1_Click()
val = 1
append val
End Sub
Private Sub key_2_Click()
val = 2
append val
End Sub
Private Sub key_3_Click()
val = 3
append val
End Sub
Private Sub key_4_Click()
val = 4
append val
End Sub
Private Sub key_5_Click()
val = 5
append val
End Sub
Private Sub key_6_Click()
val = 6
append val
End Sub
Private Sub key_7_Click()
val = 7
append val
End Sub
Private Sub key_8_Click()
val = 8
append val
End Sub
Private Sub key_9_Click()
val = 9
append val
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If (KeyAscii > 47 And KeyAscii < 58) Then
val = KeyAscii
append val
Else
KeyAscii = 0
' Text1.Text = KeyAscii
End If
End Sub
'Private Sub Text1_LostFocus()
' Text1.SetFocus
'End Sub

You could set the KeyPreview property on the form to true.
When you have done that, put your code in the KeyPress of the form that was in the KeyPress of the Textbox, and set the text value of the textbox, or better still move the code into a function and set it from there, that way you won't need to duplicate your code if you need it in other places.
Have a look at this and see if it helps it is the KeyPreview from MSDN
Hi,
Sorry for the delay. To use the KeyPreview for the form give this a try:
Double click on the form in the project to open it
In the properties for the form find the KeyPreview Property and set it to true
Double click on the form to bring up the code window
Select the keypress event for the form, and add the following code, or something similar.
Private Sub Form_KeyPress(KeyAscii As Integer)
Text1.Text = Text1.Text & Chr$(NrOnly(KeyAscii))
End Sub
Use the function NrOnly that Hqrls has posted as that will allow only numbers which could help you with the validation. You won't need any code in the Text1_KeyPress, the form will now handle that for you.
Give it a try and let me know if you need any other information and I'll see what I can do.
[EDIT 29/05/2014]
Hi,
I've had a bit of a play around with the code and added some bits in which I think might help. Have a look at this and see if it make sense. If you copy it into your code then make sure you back up your original code just in case you need to get back to it.
This is the code if you keep your textbox
Option Explicit
Dim val As String
Dim m_blnTextHasFocus As Boolean 'Added this, so it knows wether the the textbox
'has the focus or not
'it is so the sendkeys doesn't get stuck in a
'loop with the key presses
Private Sub append(strIn As String)
'Changed the parameter from an int to a string, so we can use it in the key press events
Text1.Text = Text1.Text & strIn
End Sub
Private Sub Backspace_Click()
'Moved the code into it's own sub
DeleteAChar
End Sub
Private Sub Form_KeyPress(KeyAscii As Integer)
'Handle a key press if the textbox doesn't have the focus but ignore the keypress if it does
If Not m_blnTextHasFocus Then
If IsNumeric(Chr$(KeyAscii)) Then
append Chr$(KeyAscii)
ElseIf KeyAscii = vbKeyBack Then
DeleteAChar
End If
End If
End Sub
Private Sub key_0_Click()
val = "0"
append val
End Sub
Private Sub key_1_Click()
val = "1"
append val
End Sub
Private Sub key_2_Click()
val = "2"
append val
End Sub
Private Sub key_3_Click()
val = "3"
append val
End Sub
Private Sub key_4_Click()
val = "4"
append val
End Sub
Private Sub key_5_Click()
val = "5"
append val
End Sub
Private Sub key_6_Click()
val = "6"
append val
End Sub
Private Sub key_7_Click()
val = "7"
append val
End Sub
Private Sub key_8_Click()
val = "8"
append val
End Sub
Private Sub key_9_Click()
val = "9"
append val
End Sub
Private Sub Text1_GotFocus()
m_blnTextHasFocus = True
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
'Check the keyascii value and ignore it if it isn't numeric or backspace
If Not IsNumeric(Chr$(KeyAscii)) And KeyAscii <> vbKeyBack Then
KeyAscii = 0
End If
End Sub
Private Sub DeleteAChar()
With Text1
'FOCUS TO THE TEXTBOX
.SetFocus
'PUT THE CURSOR AT THE END OF THE TEXT
.SelStart = Len(.Text)
'SEND THE KEY
SendKeys ("{BACKSPACE}")
'AND THATS IT :D
End With
End Sub
Private Sub Text1_LostFocus()
m_blnTextHasFocus = False
End Sub
If you don't need to keep the textbox then you could replace it with a label and have a try with that. It would remove the need to keep track of if the textbox has got the focus or not. Have a go with this and see if it helps any. The only other thing is to make sure KeyPreview is turned on for the form or the keypress code will only work for the form if it has the focus.

Is the textbox the only control you want to have the focus ?
In that case you can use the following code:
Private Sub Text1_LostFocus()
Text1.SetFocus
End Sub
If there are any other controls you want to be able to have the focus as well, then you can use Text1.SetFocus in the _GotFocus() event of the controls which you do not want to have the focus
Another possible solution would be to use the _KeyPress() event of the other controls as well, and convert your current Text1_KeyPress() event to a general function which can be called by the _KeyPress() event of the other controls .. make sure though that you send the output of this general function to the correct textbox
If you post the relevant parts of your code we might be able to give a more specific answer
[EDIT]
for the answer to your original question, go with the answer of lardymonkey using keypreview on the form
an example function for allowed only numeric keys and the backspace:
Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = NrOnly(KeyAscii)
End Sub
Private Function NrOnly(intAscii As Integer) As Integer
Dim intReturn As Integer
intReturn = intAscii
Select Case intAscii
Case vbKeyBack
Case vbKey0 To vbKey9
Case Else
intReturn = 0
End Select
NrOnly = intReturn
End Function

Related

VB6 How to return a string value from form2 to form 1

in my project there are two forms:
first form i named it frmSettings , i will use text boxes to save values in INI file.
second form i named it frmSelectFolder , i had included with DirListBox and 2 Command buttons
as shown in attached image above in Settings form i have 8 text boxes and 8 command buttons to browse for folder path that it will be selected from frmSelectFolder
how to use frmSelectFolder for all text boxes without duplicating this form per each command button to return DirlistBox Control value ?
Here is some sample code for secondary frmSelectFolder form
Option Explicit
Private m_bConfirm As Boolean
Public Function Init(sPath As String) As Boolean
Dir1.Path = sPath
Show vbModal
If m_bConfirm Then
sPath = Dir1.Path
'--- success
Init = True
End If
Unload Me
End Function
Private Sub cmdOk_Click()
If LenB(Dir1.Path) = 0 Then
MsgBox "Please select a path!", vbExclamation
Exit Sub
End If
m_bConfirm = True
Visible = False
End Sub
Private Sub cmdCancel_Click()
Visible = False
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If UnloadMode <> vbFormCode Then
Cancel = 1
Visible = False
End If
End Sub
Here is how to call Init method above from primary frmSettings
Option Explicit
Private Sub cmdStartupPath_Click()
Dim sPath As String
Dim oFrmSelector As New frmSelectFolder
sPath = txtStartupPath.Text
If oFrmSelector.Init(sPath) Then
txtStartupPath.Text = sPath
txtStartupPath.SetFocus
End If
End Sub
Private Sub cmdDownloadPath_Click()
Dim sPath As String
Dim oFrmSelector As New frmSelectFolder
sPath = txtDownloadPath.Text
If oFrmSelector.Init(sPath) Then
txtDownloadPath.Text = sPath
txtDownloadPath.SetFocus
End If
End Sub
Here is a link to a complete sample project for you to research: SelectFolder.zip

callbyname vb6 using string as argument

I am trying to set some images's visibility to false by using CallByName and a loop through the objects.
here is the code
Private Sub command1Click
dim theobj_str as string
dim ctr as integer
for ctr = 1 to 3
theobj_str = "Images" & ctr
CallByName theobj_str, "Visible", vbLet,False
end for
END SUB
It throws an error "TYPE MISMATCH" on "CallByName **theobj_str**..."
The CallByName takes an object as its first argument. I need to somehow convert the string "theobj_str" into an object. How can I do this ?
The CallByName works fine if I call it like : CallByName Images2, "Visible", vbLet,False
Thanks
If you don't need to use CallByName you could loop through the controls collection and check the type. If the type matches the control you want to hide then you can set it's visible property that way.
The code would look like this:
Private Sub Command_Click()
SetControlVisibility "Image", False
End Sub
Private Sub SetControlVisibility(ByVal controlType As String, ByVal visibleValue As Boolean)
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = controlType Then
ctrl.Visible = visibleValue
End If
Next
End Sub
Doing it this way will allow you to add more image controls to your form without having to remember to change your counts in the for loop.
Hope that helps.

excel vba userform picture change on click

I made a userform with 10 * 4 spaces for pictures("set11", "set12", ...). At the beginning they are empty. When I click on one of the pictures they should be reset by a random picture(function getRandomPath).
The sub "clicked" works if I use a Button(start) to click. If I click a picture nothing happens. When I now click again on the Button(start), the before clicked pictures don't change no more.
Here is the relevant code:
Private Sub set11_Click()
Call clicked("1", "1") '*doesn't work*
End Sub
Private Sub set12_Click()
Call clicked("1", "2") '*doesn't work*
End Sub
Private Sub set13_Click()
Call clicked("1", "3") '*doesn't work*
End Sub
Private Sub set14_Click()
Call clicked("1", "4") '*doesn't work*
End Sub
Private Sub clicked(row As String, column As String)
Controls("set" & row & column).Picture = LoadPicture(getRandomPfad())
End Sub
Private Sub start_Click()
Call clearpictures
set11.Picture = LoadPicture(getRandomPfad()) '*works*
Controls("set12").Picture = LoadPicture(getRandomPfad()) '*works*
Call clicked("1", "3") '*works*
End Sub
Private Function getRandomPfad()
Dim random As Integer
random = Int(6 * Rnd + 1)
Select Case random
Case Is = 1
getRandomPfad = "U:\MMpic\Green.jpg"
Case Is = 2
getRandomPfad = "U:\MMpic\Blue.jpg"
Case Is = 3
getRandomPfad = "U:\MMpic\Yellow.jpg"
Case Is = 4
getRandomPfad = "U:\MMpic\Pink.jpg"
Case Is = 5
getRandomPfad = "U:\MMpic\Orange.jpg"
Case Is = 6
getRandomPfad = "U:\MMpic\Red.jpg"
End Select
End Function
I hope you can help me.
Your code must exist inside the userform. If the code is within a Module, it will not work.
Also, ensure you have named the image controls to match the names given in your code: "set11"
I found the solution, I should have repainted:
Private Sub clicked(row As String, column As String)
Controls("set" & row & column).Picture = LoadPicture(getRandomPfad())
Repaint
End Sub
But thank you for your help!

procedure declaration does not match description of event or procedure having the same name

I am just novice and I tried to make a simple program in Visual Basic 6. The code is almost equivalent to that in the textbook. It was meant to be a kind of a paint program. Surprisingly, it couldn't be compiled with the error given in the title of this question.
This is the code:
Option Explicit
Dim Col As Long
Private Sub Form_Load()
AutoRedraw = True
BackColor = vbWhite
Col = vbBlack
DrawWidth = 3
End Sub
Private Sub Command1_Click()
CommonDialog1.ShowOpen
Form1.Picture = LoadPicture(CommonDialog1.FileName)
End Sub
Private Sub Command2_Click()
CommonDialog1.ShowSave
SavePicture Image, CommonDialog1.FileName
End Sub
Private Sub Command3_Click()
CommonDialog1.ShowColor
Col = CommonDialog1.Color
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
PSet (X, Y), Col
End Sub
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)
Select Case Button.Key
Case "Line1"
DrawWidth = 3
Case "Line2"
DrawWidth = 20
End Select
End Sub
The application crashes on the following line:
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)
With the error:
procedure declaration does not match description of event or procedure
having the same name
The problem is here:
Private Sub Toolbar1_ButtonClick(ByVal Button As MSComctlLib.Button)
Ok, since you are coding in VB6, you get to learn some of the tricks in the VB6 playbook. Temporarily rename the method to something else like qqToolbar_ButtonClick, then go to the designer and click the button in the toolbar to regenerate the event in the code.
In the event that the signature has been mistyped, it will regenerate from the designer correctly and you might see the issue.
Another check is to see if the ToolBar1 was added to a control array? In that case, the method signature needs to look like this:
Private Sub Toolbar1_ButtonClick(ByVal Index as Integer, ByVal Button As MSComctlLib.Button)
I hope one of these helps solve the issue for you.

Auto complete text box in excel VBA

I am creating a excel sheet that would autocomplete a text based on the text present in a particular column. After trying to make one myself unsuccessfully, I was looking online for sample codes that I could modify and incorporate in my program. (and not plagiarize)
I downloaded Workbook1.xls from http://www.ozgrid.com/forum/showthread.php?t=144438
The code is
Option Explicit
Dim ufEventsDisabled As Boolean
Dim autoCompleteEnabled As Boolean
Dim oRange As Range
Private Sub TextBox1_Change()
If ufEventsDisabled Then Exit Sub
If autoCompleteEnabled Then Call myAutoComplete(TextBox1)
End Sub
Sub myAutoComplete(aTextBox As MSForms.TextBox)
Dim RestOfCompletion As String
On Error GoTo Halt
With aTextBox
If .SelStart + .SelLength = Len(.Text) Then
RestOfCompletion = Mid(oRange.Cells(1, 1).AutoComplete(.Text), Len(.Text) + 1)
ufEventsDisabled = True
.Text = .Text & RestOfCompletion
.SelStart = Len(.Text) - Len(RestOfCompletion)
.SelLength = Len(RestOfCompletion)
End If
End With
Halt:
ufEventsDisabled = False
On Error GoTo 0
End Sub
Private Sub TextBox1_AfterUpdate()
Dim strCompleted As String
With TextBox1
strCompleted = oRange.AutoComplete(.Text)
If LCase(strCompleted) = LCase(.Text) Then
ufEventsDisabled = True
.Text = strCompleted
ufEventsDisabled = False
End If
End With
End Sub
Private Sub TextBox1_Enter()
Set oRange = ThisWorkbook.Sheets("Sheet1").Range("f4")
End Sub
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
autoCompleteEnabled = KeyCode <> vbKeyBack
autoCompleteEnabled = ((vbKey0 <= KeyCode) And (KeyCode <= vbKeyZ))
End Sub
Private Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub UserForm_Click()
End Sub
If you'd notice the line RestOfCompletion = Mid(oRange.Cells(1, 1).AutoComplete(.Text), Len(.Text) + 1), I was wondering what AutoComplete is doing here. Its not a in built function and is not defined anywhere. Still the code runs fine. I am very curious.
Thanks
The .AutoComplete is a function of the Range object - it is based on passing the text to a range that exists elsewhere on the sheet.
You can see the documentation on this function here:
http://msdn.microsoft.com/en-us/library/bb209667(v=office.12).aspx
The myAutoComplete function handles the finding of the autocomplete data against the range if it exists, and the other pieces in the code are for highlighting the correct piece of text.

Resources