Guest User

Untitled

a guest
Jul 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. Imports System
  2. Imports System.Text
  3. Imports System.Drawing
  4. Imports System.IO.Ports
  5. Imports System.Windows.Forms
  6. Imports System.Threading
  7.  
  8.  
  9. Public Class Form1
  10.  
  11. Dim testo As String
  12. Public trd As Thread
  13. Delegate Sub SetTextCallback(ByVal [text] As String)
  14.  
  15. Private Sub ConfigurazioneSerialeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfigurazioneSerialeToolStripMenuItem.Click
  16. SerialPort1.Close()
  17. 'trd.Suspend()
  18. Form2.ShowDialog()
  19. ' trd.Resume()
  20. End Sub
  21.  
  22.  
  23. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  24. Form2.ShowDialog()
  25. 'trd = New Thread(AddressOf ThreadProcUnsafe)
  26. 'trd.IsBackground = True
  27. 'trd.Start()
  28. End Sub
  29.  
  30.  
  31. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  32. If SerialPort1.IsOpen = False Then
  33. SerialPort1.Open()
  34. End If
  35.  
  36. SerialPort1.Write(TextBox2.Text)
  37. TextBox1.ForeColor = Color.Blue
  38. TextBox1.Text &= "Msg Inviato:" & TextBox2.Text & vbCrLf
  39. TextBox2.Text = ""
  40. End Sub
  41.  
  42.  
  43. Private Sub ThreadProcUnsafe()
  44.  
  45. Do
  46. testo = ""
  47.  
  48. Try
  49.  
  50. SerialPort1.ReadTimeout = 500
  51.  
  52. Do
  53. Dim Incoming As String = SerialPort1.ReadLine()
  54. If Incoming Is Nothing Then
  55. Exit Do
  56. Else
  57. testo &= Incoming & vbCrLf
  58. End If
  59.  
  60. Loop
  61.  
  62.  
  63. Catch ex As TimeoutException
  64. 'testo = "Nessuno dato ricevuto"
  65. End Try
  66.  
  67. Thread.Sleep(1000)
  68.  
  69. If testo <> "" Then
  70. Me.SetText(testo)
  71. End If
  72. Loop
  73. End Sub
  74.  
  75.  
  76. Private Sub Form1_Unload(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.FormClosed
  77. 'trd.Suspend()
  78. SerialPort1.Close()
  79. End Sub
  80.  
  81.  
  82. Private Sub SetText(ByVal [text] As String)
  83.  
  84. If Me.TextBox1.InvokeRequired Then
  85. Dim d As New SetTextCallback(AddressOf SetText)
  86. Me.Invoke(d, New Object() {[text]})
  87. Else
  88. Me.TextBox1.Text = [text]
  89. End If
  90. End Sub
  91.  
  92.  
  93. Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
  94. testo = ""
  95. System.Threading.Thread.Sleep(300)
  96. testo = (SerialPort1.ReadExisting)
  97.  
  98. If testo <> "" Then
  99. TextBox1.ForeColor = Color.Red
  100. TextBox1.Text &= "Msg Ricevuto:" & testo & vbCrLf
  101. End If
  102.  
  103. End Sub
  104.  
  105. End Class
Add Comment
Please, Sign In to add comment