Не работает скомпилированный ехе файл (работа с СОМ портом) - VB

Узнай цену своей работы

Формулировка задачи:

закончил написание приложения для работы с ком портом за основу брал исходник http://www.sources.ru/vb/vb_serial_comms.shtml т.о. обращался с ком портом через API функцию. вот модуль
Листинг программы
  1. Option Explicit
  2. Global ComNum As Long
  3. Global bRead(1535) As Byte
  4. Type COMSTAT
  5. fCtsHold As Long
  6. fDsrHold As Long
  7. fRlsdHold As Long
  8. fXoffHold As Long
  9. fXoffSent As Long
  10. fEof As Long
  11. fTxim As Long
  12. fReserved As Long
  13. cbInQue As Long
  14. cbOutQue As Long
  15. End Type
  16. Type COMMTIMEOUTS
  17. ReadIntervalTimeout As Long
  18. ReadTotalTimeoutMultiplier As Long
  19. ReadTotalTimeoutConstant As Long
  20. WriteTotalTimeoutMultiplier As Long
  21. WriteTotalTimeoutConstant As Long
  22. End Type
  23. Type DCB
  24. DCBlength As Long
  25. BaudRate As Long
  26. fBinary As Long
  27. fParity As Long
  28. fOutxCtsFlow As Long
  29. fOutxDsrFlow As Long
  30. fDtrControl As Long
  31. fDsrSensitivity As Long
  32. fTXContinueOnXoff As Long
  33. fOutX As Long
  34. fInX As Long
  35. fErrorChar As Long
  36. fNull As Long
  37. fRtsControl As Long
  38. fAbortOnError As Long
  39. fDummy2 As Long
  40. wReserved As Integer
  41. XonLim As Integer
  42. XoffLim As Integer
  43. ByteSize As Byte
  44. Parity As Byte
  45. StopBits As Byte
  46. XonChar As Byte
  47. XoffChar As Byte
  48. ErrorChar As Byte
  49. EofChar As Byte
  50. EvtChar As Byte
  51. End Type
  52. Type OVERLAPPED
  53. Internal As Long
  54. InternalHigh As Long
  55. offset As Long
  56. OffsetHigh As Long
  57. hEvent As Long
  58. End Type
  59. Type SECURITY_ATTRIBUTES
  60. nLength As Long
  61. lpSecurityDescriptor As Long
  62. bInheritHandle As Long
  63. End Type
  64. Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
  65. Declare Function GetLastError Lib "kernel32" () As Long
  66. Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As Long) As Long
  67. Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As Long) As Long
  68. Declare Function SetCommTimeouts Lib "kernel32" (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As Long
  69. Declare Function GetCommTimeouts Lib "kernel32" (ByVal hFile As Long, lpCommTimeouts As COMMTIMEOUTS) As Long
  70. Declare Function BuildCommDCB Lib "kernel32" Alias "BuildCommDCBA" (ByVal lpDef As String, lpDCB As DCB) As Long
  71. Declare Function SetCommState Lib "kernel32" (ByVal hCommDev As Long, lpDCB As DCB) As Long
  72. Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
  73. Declare Function FlushFileBuffers Lib "kernel32" (ByVal hFile As Long) As Long
  74.  
  75. Function fin_com()
  76. fin_com = CloseHandle(ComNum)
  77. End Function
  78. Function FlushComm()
  79. FlushFileBuffers (ComNum)
  80. End Function
  81. Function Init_Com(ComNumber As String, Comsettings As String) As Boolean
  82. On Error GoTo handelinitcom
  83. Dim ComSetup As DCB, Answer, Stat As COMSTAT, RetBytes As Long
  84. Dim retval As Long
  85. Dim CtimeOut As COMMTIMEOUTS, BarDCB As DCB
  86. ' Open the communications port for read/write (&HC0000000).
  87. ' Must specify existing file (3).
  88. ComNum = CreateFile(ComNumber, &HC0000000, 0, 0&, &H3, 0, 0)
  89. If ComNum = -1 Then
  90. 'MsgBox "Com Port " & ComNumber & " not available. Use Serial settings (on the main menu) to setup your ports.", 48
  91. Init_Com = False
  92. Exit Function
  93. End If
  94. 'Setup Time Outs for com port
  95. CtimeOut.ReadIntervalTimeout = 20
  96. CtimeOut.ReadTotalTimeoutConstant = 1
  97. CtimeOut.ReadTotalTimeoutMultiplier = 1
  98. CtimeOut.WriteTotalTimeoutConstant = 10
  99. CtimeOut.WriteTotalTimeoutMultiplier = 1
  100. retval = SetCommTimeouts(ComNum, CtimeOut)
  101. If retval = -1 Then
  102. retval = GetLastError()
  103. MsgBox "Unable to set timeouts for port " & ComNumber & " Error: " & retval
  104. retval = CloseHandle(ComNum)
  105. Init_Com = False
  106. Exit Function
  107. End If
  108. retval = BuildCommDCB(Comsettings, BarDCB)
  109. If retval = -1 Then
  110. retval = GetLastError()
  111. MsgBox "Unable to build Comm DCB " & Comsettings & " Error: " & retval
  112. retval = CloseHandle(ComNum)
  113. Init_Com = False
  114. Exit Function
  115. End If
  116. retval = SetCommState(ComNum, BarDCB)
  117. If retval = -1 Then
  118. retval = GetLastError()
  119. MsgBox "Unable to set Comm DCB " & Comsettings & " Error: " & retval
  120. retval = CloseHandle(ComNum)
  121. Init_Com = False
  122. Exit Function
  123. End If
  124. Init_Com = True
  125. handelinitcom:
  126. Exit Function
  127. End Function
  128. Function ReadCommPure() As String
  129. On Error GoTo handelpurecom
  130. Dim RetBytes As Long, i As Integer, ReadStr As String, retval As Long
  131. Dim CheckTotal As Integer, CheckDigitLC As Integer
  132. retval = ReadFile(ComNum, bRead(0), 1535, RetBytes, 0)
  133. ReadStr = ""
  134. If (RetBytes > 0) Then
  135. For i = 0 To RetBytes - 1
  136. ReadStr = ReadStr & Chr(bRead(i))
  137. Next i
  138. Else
  139. FlushComm
  140. End If
  141. 'Return the string read from serial port
  142. ReadCommPure = ReadStr
  143. handelpurecom:
  144. Exit Function
  145. End Function
  146. Function WriteCOM32(COMString As String) As Integer
  147. On Error GoTo handelwritelpt
  148. Dim RetBytes As Long, LenVal As Long
  149. Dim retval As Long
  150. Dim BB As Byte
  151. If COMString = 1 Then BB = &H55
  152. If COMString = 2 Then BB = &H75
  153. If COMString = 3 Then BB = &H85
  154. retval = WriteFile(ComNum, BB, 1, RetBytes, 0)
  155. WriteCOM32 = RetBytes
  156. handelwritelpt:
  157. Exit Function
  158. End Function
вызываю функцию кнопкой (в текст2 команда 1,2 или 3)
Листинг программы
  1. Private Sub Command1_Click()
  2. If WriteCOM32(txt(2)) <> Len(txt(2)) Then 'проверка записываемой команды
  3. MsgBox "Error writing to comm's"
  4. Exit Sub
  5. End If
  6. 'далее мои операторы
  7. *****
так вот,когда запускаю все это в редакторе VB 6 все работает нормально. А скомпеллированный ЕХЕ файл не работает, пишет ошибку MsgBox "Error writing to comm's". Пробовал пошагово вставлять MsgBox'ы, определил что не срабатывает WriteFile(ComNum, BB, 1, RetBytes, 0) думал, что проблемы с библиотекой "kernel32", но функция sleep (из другого модуля) в ЕХЕшнике работает
Листинг программы
  1. Declare Sub sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
  2. Sub Sleep1(timee As Long)
  3. sleep timee
  4. End Sub
кто-нибудь знает, в чем может быть дело?

Решение задачи: «Не работает скомпилированный ехе файл (работа с СОМ портом)»

textual
Листинг программы
  1. txt(2).text

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 4.4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут