I created a tcp connection in vb6 to grab the weight off of a scale and display that weight after pressing a button. The problem is that the weight is not displayed until the SECOND (2nd) click of the button, not the first. I have set a break point in various spots and upon the first click of the button, it takes me to that break point, so I know the event is firing as it should, but nothing is displayed until the 2nd click. I have done a bunch of research but can't seem to find anyone with the exact problem (or solution).
Public tcpC As New Winsock
'Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub CFixPicture_Close()
tcpC.Close
End Sub
Private Sub CFixPicture_Initialize()
tcpC.LocalPort = 0
tcpC.Connect "192.168.0.1", 8000
End Sub
Private Sub CommandButton1_click()
On Error GoTo errHandler
Dim strData As String
tcpC.SendData "S" & vbCrLf
tcpC.GetData strData
Text1.Caption = "Weight: " & strData
Exit Sub
errHandler:
MsgBox "error:" & Err.Description
End Sub
I am making an assumption that your code is in the form and you are just declaring a new object of type Winsock. My code declares a Winsock variable using the keyword WithEvents to get access to the events raised by the Winsock object. The particular event you're interested in is DataArrival. It is fired by the Winsock control when data is received. I moved setting the text to this event. Also, you cannot use WithEvents and "As New" (you really don't want to use As New anyway), so I create the object before I set the properties in the CFixPicture_Initialize() method. Finally, I added setting the object to nothing after closing it.
Option Explicit
Private WithEvents tcpC As Winsock
Private Sub CFixPicture_Close()
tcpC.Close
Set tcpP = Nothing
End Sub
Private Sub CFixPicture_Initialize()
Set tcpC = New Winsock
tcpC.LocalPort = 0
tcpC.Connect "192.168.0.1", 8000
End Sub
Private Sub CommandButton1_click()
On Error GoTo errHandler
Dim strData As String
tcpC.SendData "S" & vbCrLf
'there is no data here yet - moved to the DataArrival event
'tcpC.GetData strData
'Text1.Caption = "Weight: " & strData
Exit Sub
errHandler:
MsgBox "error:" & Err.Description
End Sub
Private Sub tcpC_DataArrival(ByVal bytesTotal As Long)
Dim strData As String
tcpC.GetData strData
Text1.Caption = "Weight: " & strData
End Sub