按钮事件在第二次单击之前不显示值(vb6)

时间:2015-07-13 19:36:52

标签: tcp vb6 winsock commandbutton

我在vb6中创建了一个tcp连接来获取刻度的重量,并在按下按钮后显示该重量。问题是,在按钮的第二次(第二次)点击之前不显示重量,而不是第一次。我在各个位置都设置了一个断点,在第一次点击按钮时,它会将我带到那个断点,所以我知道事件正在按照它应该触发,但是直到第二次点击才会显示任何内容。我做了很多研究,但似乎找不到任何有确切问题(或解决方案)的人。

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

1 个答案:

答案 0 :(得分:1)

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