I want my program to show a msgbox / error message if you open the SerialPort and the connected device doesn't respond.
I tried to use the ReadTimeout property but i am assuming i can't put it in the "DataReceived" event as that will never be triggered when the connected device sends no data?
Do i have to make a seperate ReadExisting command e.g. in a timer to use the ReadTimeout?
My code looks like this at the moment
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
SerialPort1.ReadTimeout = 2000
Try
datastr = SerialPort1.ReadExisting
Catch ex As TimeoutException
msgbox(ex.message)
End Try
TiA
Related
Hello I have this project experiencing some problems with what is supposed to be my codes for the "problem" handler.
Public Event UnhandledException As UnhandledExceptionEventHandler
Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
End Sub
Sub MyHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(Date.now & e.toString)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
Application.Exit()
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Throw New Exception("Dummy Error")
End Sub
I'm trying to globally catch all exceptions and create logfile during runtime, which works fine in the debugger(exception handling and textfile writing) but cannot catch any unhandled exceptions after I build it in the setup project and Installed into a machine. What am I missing? Do I need to include additional components to my setup project? Help would be greatly appreciated
There is already a way to handle exceptions for the entire application. Embedding the handler in a form means they would only be caught and logged if and while that form was open.
Go to Project -> Properties -> Application and click the "View Application Events" button at/near the bottom.
This will open ApplicationEvents.vb.
Select (MyApplicationEvents) in the left menu; and UnhandledException in the right. This opens an otherwise typical event handler to which you can add code:
Private Sub MyApplication_UnhandledException(sender As Object,
e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim myFilePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"badjuju.log")
Using sw As New StreamWriter(File.Open(myFilePath, FileMode.Append))
sw.WriteLine(DateTime.Now)
sw.WriteLine(e.Exception.Message)
End Using
MessageBox.Show("An unexcpected error occured. Application will be terminated.")
End
End Sub
This will not catch exceptions while the IDE is running because VS catches them first so you can see them and fix them.
I am trying to edit open source code i found, there is allot of bugs there, anyway i solve everything but i still have this one:
i put a combo drop-down menu to chose between serial ports to communicate with arduino, but it seems always the program chose COM5 if i chose other port or not.
this is the error i have when i press start button to communicate
An unhandled exception of type 'System.IO.IOException' occurred in System.dll
Additional information: The port 'COM5' does not exist.
and this is the combo drop-down menu code
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Handles ComboBox1.SelectedIndexChanged
End Sub
and this code for the start button
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs)
Handles Button7.Click
SerialPort1.Open()
SerialPort1.Write("~")
SerialPort1.Write("LCD is working!")
Timer2.Start()
SerialPort1.Close()
End Sub
but it seems always the program chose COM5 if i chose other port or not. this is the error i have when i press start button to communicate
This code
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
is intended to get the combo box index selected by a user and set which serial port they selected. However, the body of that handler is empty, so it is not actually doing anything.
The code
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
SerialPort1.Open()
is presumably where the Exception is being thrown. You have not changed the settings of SerialPort1 anywhere in the code you show. Presumably, you should add some code to ComboBox1_SelectedIndexChanged to update the properties of SerialPort1 to reflect the COM port the user selected.
I have 3 different computers in 3 different locations ,and i need to build a software that can control these 3 computers using vb.net,my basic need is to play a video on my server system ,and i need these 3 computers to play the same video at the same time , how can i send and recieve wireless data using vb.net
You can upload the video to any video hosting site and then use this code to send a message to the computers (using there public IP adress where stated):
Public Class MessageReciever
Dim Listener As New TcpListener(5534) 'or any unused port
Dim Client As TcpClient
Private Sub MessageReciever_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Listener.Stop()
End Sub
Private Sub MessageReciever_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
Listener.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim message As String
Dim nStart As Integer
Dim nLast As Integer
If Listener.Pending = True Then
message = ""
Client = Listener.AcceptTcpClient()
Dim reader As New StreamReader(Client.GetStream())
While reader.Peek > -1
message &= Convert.ToChar(reader.Read()).ToString
End While
If message.Contains("</>") Then
nStart = InStr(message, "</>") + 4
nLast = InStr(message, "<\>")
message = Mid(message, nStart, nLast - nStart)
End If
End If
If message = "playVideo" then
Process.start("http://youtube.com/watch?yourvideo") 'opens website in default browser
End If
End Sub
End Class
Import all the stuff it tells you to.
If you put this software on the computers you would like to play the video on and then put the following code on the main computer you would like to control the others on:
Option Explicit On
Public Class MessageSender
Dim client As TcpClient
Private Sub PlayVidButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PlayVidButton.Click
Try
client = New TcpClient(computer ur controllings public ip, 5534) 'you can get your public ip # portforward.com and make sure the port here is the same as the one entered for the listener in the other form
Dim writer As New StreamWriter(client.GetStream())
writer.Write("playVideo")
writer.Flush()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I hope this helps your problem.
I was trying to make a file unlocker which get process which using the file and get it killed to make it able to be deleted. It was okay when my targeted file is a WMP file. But I can't get it work when it comes to dll and iso. I got the problem on this line:
Which is used to get the process name. Any help is appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnShow.Click
Dim files As New List(Of String)
files.Add(OpenFileDialog1.FileName)
Dim Processes As List(Of Process) = Util.GetProcessesUsingFiles(files)
RichTextBox1.AppendText(vbCrLf & "Processes that using the file is:")
For Each p As Process In Processes
TextBox1.Text = (Path.GetFileName(p.MainModule.FileName))
TextBox1.Text = TextBox1.Text.Replace(".exe", "")
Next
Timer1.Start()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnKill.Click
If TextBox1.Text = ("Nothing") Then
MsgBox("No proccess is using that file.")
ElseIf MsgBox("Proccess(es) killed") Then
End If
For Each p As Process In System.Diagnostics.Process.GetProcessesByName(Path.GetFileName(TextBox1.Text))
Try
p.Kill()
' possibly with a timeout
p.WaitForExit()
' process was terminating or can't be terminated - deal with it
Catch winException As Win32Exception
' process has already exited - might be able to let this one go
Catch invalidException As InvalidOperationException
End Try
Next
I've already got the solution. Just add Try..Catch..
Hello there I'm encountering an issue recently and been searching more than two months but haven't found a solution for it yet. I have to write a program/application (which I already started in VB.NET 2010) that connects through Panasonic KX-TEM824 PBX machine via RS232 port (cable already connected : COM15/16 depending on USB I connect) and while it's connected to parse(receive) the data from the PBX itself, data that has caller ID, time of call started and ended, duration of the call and etc. I have found some already application on the Internet that does the work but they are free to try after awhile requires to buy or restart the app again. But I assume there's not much to implement on the code side. Please I really need help. I'm posting code below. P.s. it's for study purpose.
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class frmMain
Dim myPort As Array 'COM Ports detected on the system will be stored here
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'When our form loads, auto detect all serial ports in the system and populate the cmbPort Combo box.
myPort = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available
cmbBaud.Items.Add(9600) 'Populate the cmbBaud Combo box to common baud rates used
cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)
cmbBaud.Items.Add(115200)
For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next
cmbPort.Text = cmbPort.Items.Item(0) 'Set cmbPort text to the first COM port detected
cmbBaud.Text = cmbBaud.Items.Item(0) 'Set cmbBaud text to the first Baud rate on the list
btnDisconnect.Enabled = False 'Initially Disconnect Button is Disabled
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text 'Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Text 'Set Baud rate to the selected value on
'Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8 'Open our serial port
SerialPort1.Open()
btnConnect.Enabled = False 'Disable Connect button
btnDisconnect.Enabled = True 'and Enable Disconnect button
End Sub
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close() 'Close our Serial Port
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text & vbCr) 'The text contained in the txtText will be sent to the serial port as ascii
'plus the carriage return (Enter Key) the carriage return can be ommitted if the other end does not need it
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting()) 'Automatically called every time a data is received at the serialPort
End Sub
Private Sub ReceivedText(ByVal [text] As String)
'compares the ID of the creating Thread to the ID of the calling Thread
If Me.rtbReceived.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.rtbReceived.Text &= [text]
End If
End Sub
Private Sub cmbPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPort.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.PortName = cmbPort.Text 'pop a message box to user if he is changing ports
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
Private Sub cmbBaud_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaud.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.BaudRate = cmbBaud.Text 'pop a message box to user if he is changing baud rate
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
End Class
I also have this PBX unit, so im curious now, but I cant check it out till im back at work tomorrow.
This code looks like a msdn sample code, and has not been customised in any way for the pbx applicatiom. Perhaps you should do as hans suggested and get it working with a terminal program first, then set up your app with only the correct baud, parity and stop bits. IIRC the panasonic uses fixed settings, therefore providing options will just complicate the issue.