I built a DLL with Visual Basic 2010 Express. It's built on the VB 4.0 framework. After building, I ran on the admin command prompt:
C:\windows\...v4.0.30319\RegAsm C:\...\bin\release\ClassLibrary1.dll
The COM-visible check box is already checked. But my other program can't connect to it, with the error message mentioned in the title.
The class library only contains 1 class. It's in SMSCOMMS.vb:
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New()
End Sub
Public Sub initPort(ByVal COMMPORT As String)
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function testFunction() As Integer
Return 1
End Function
Public Function SendSMS(ByVal receiver As String, ByVal message As String) As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT+CMGF=1" & Chr(13)) 'set command message format to text mode(1)
'SMSPort.WriteLine("AT+CSCA=+639170000130" & Chr(13)) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS=" & Chr(34) & receiver & Chr(34) & Chr(13)) ' enter the mobile number whom you want to send the SMS
SMSPort.WriteLine(message & Chr(26)) 'SMS sending
SMSPort.Close()
Return True
End If
Return False
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
I used visual basic 2012 instead. There's a checkbox for Com interop.
Related
I am studying VB.NET and threading.
I tried thread method to dynamically update status on GUI part.
However, GUI randomly freeze after 10-20 mins running.
I am not sure what i missing.
On form1 : I have textbox and label to update on GUI
Imports System.IO
Imports System.Threading
Public Class form1
package.add("sleep_time",3)
Private Sub BT_START_Click(sender As Object, e As EventArgs) Handles BT_START.Click
Start(package)
end sub
public sub Start(package as hashtable)
Dim t As System.Threading.Thread
t = New Thread(New ThreadStart(Sub() Update.run(Me, Package)))
t.IsBackground = True
t.Start()
end sub
End Class
On run.vb file we update label: Label_status and textbox : text_box_status
Imports System.Threading
Imports System.IO
Public Class Update
public sub run(myform as form1, pakcage as hashtable)
for i to 10000
myform.Label_status.text = "Try: " + i.tostring()
update_text_box(myform.text_box_status, "Try: " + i.tostring())
Thread.Sleep(3* 1000)
end for
end sub
public sub update_text_box(MF as textbox, SYS_MSG as string)
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
MF.AppendText(SYS_MSG & vbNewLine)
MF.Select(MF.TextLength, 0)
MF.ScrollToCaret()
files.Write(SYS_MSG & vbNewLine)
end sub
end class
i check Thread updating GUI freezes in random moments
Windows Form application freeze randomly when run overnight
I am assuming that I am missing invoke or delegate methods
However, I am not clear sure why this happens. Is there anything that i missed to use thread and update Label and textbox on form?
thanks!
Try it like this instead:
private t As System.Threading.Thread
public sub Start(package as hashtable)
if isnothing(t) then
t = New Thread(New ThreadStart(Sub() Update.run(Me, Package)))
t.IsBackground = True
t.Start()
end if
end sub
With:
Public Sub run(myform As Form1, package As Hashtable)
For i As Integer = 1 To 10000
Dim msg As String = "Try: " + i.ToString()
myform.Invoke(Sub()
myform.Label_status.text = msg
Dim MF As TextBox = myform.text_box_status
MF.AppendText(SYS_MSG & vbNewLine)
MF.Select(MF.TextLength, 0)
MF.ScrollToCaret()
update_text_box(myform.text_box_status, msg)
End Sub)
files.Write(SYS_MSG & vbNewLine)
Thread.Sleep(TimeSpan.FromSeconds(3).TotalMilliseconds)
Next
End Sub
I have written an vb.net class which I want to make COM-visible for VB6. I have an old application which was developed in VB6, and I am in the process of rewrite it entirely for .net, but in the meantime I need to get this class working and get it usable together with VB6.
All the methods exposed to COM seems to work as they should, but I can't get the event to work with VB6. I have crawled the net for weeks now, and have found a lot of information which have helped me to the point I am now. The problem is when I try to select the class in the dropdown list inside the VB6 IDE, the IDE creates an eventhandler directly(in my case sub tc_Pls_changeprice()). What's strange is that it's not possible for me to select or mark the actual class, and then pick the event from the event dropdown list.
If I doesn't try to select the class first, but select the event directly from the event dropdownlist, I am able to select it(but the name of it is tc_Pls_changeprice, and not Pls_changeprice as I should expect)
If I select it two or more times, the IDE generates new eventhandlers rather than jump into the already created eventhandler.
When I try to put code inside the eventhandler, my vb6 testapplication compiles and run, but the event doesn't fire.
I have attached my .net code and my vb6 testapplication code.
The .dll has been compiled with ComVisible activated, but not register as com-interop(since I need to register the dll on other machines). I register the dll on the host machines with regasm /TLB /codebase option, and the TLB that is generated is located together with the DLL inside same directory as my vb6 source directory.
Duplicate eventhandlers:
This picture shows that its something wrong with the event dropdown event list, and I'm not able to first select the class from the left dropdown list:
Have anybody any ideas of what's wrong?
Here is my .net code for the class:
Imports System.IO.Ports
Imports System.Timers
<Guid("ABEF0C71-17CE-4d38-BEFD-71770E7D50B4")>
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
<ComVisible(True)>
Public Interface Itaxcomm
<DispId(1)> Property commport As String
<DispId(2)> ReadOnly Property taxstatus As String
<DispId(3)> Function open() As Integer
<DispId(4)> Function close() As Integer
<DispId(5)> Sub testevent()
<DispId(6)> Sub Reset()
<DispId(7)> Sub ChangepriceOK()
<DispId(8)> Sub Triggerstartbutton()
<DispId(9)> Sub TaxState()
End Interface
<Guid("A68C5882-21B2-4827-AA0F-A8D6538D1AE3")>
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
<ComVisible(True)>
Public Interface ItaxcommEvents
<DispId(10)> Sub Pls_changeprice()
End Interface
<ComVisible(True)>
<ClassInterface(ClassInterfaceType.None)>
<ComDefaultInterface(GetType(Itaxcomm))>
<ComSourceInterfaces(GetType(ItaxcommEvents))>
<Guid("0F998406-B0CF-440a-8A78-262015480C90")>
<ProgId("Taxcomm.taxcomm")>
Public Class taxcomm
Implements Itaxcomm
Public Status As String
<ComVisible(False)>
Public Delegate Sub pls_changepricedelegate()
Public Event Pls_changeprice As pls_changepricedelegate
Private _comport As String
Private _taxmode As String
Private rxByte(4096) As Byte
Private WithEvents statetimer As New Timer
Private WithEvents sp As New SerialPort
Private Property Itaxcomm_commport As String Implements Itaxcomm.commport
Get
Return _comport
End Get
Set(ByVal value As String)
_comport = value
End Set
End Property
Private ReadOnly Property Itaxcomm_taxstatus As String Implements Itaxcomm.taxstatus
Get
Return _taxmode
End Get
End Property
Private Sub sp_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim s As String = ""
If sp.BytesToRead < 7 Then Exit Sub
sp.Read(rxByte, 0, 7)
For i = 0 To 20
s = s + (rxByte(i).ToString) & " "
Next i
If rxByte(0) = &H48 And rxByte(6) = &H54 And rxByte(5) = (rxByte(0) Xor rxByte(1) Xor rxByte(2) Xor rxByte(3) Xor rxByte(4)) Then
Select Case rxByte(3)
Case 0
Select Case rxByte(4)
Case 0 ''Normal_mode(with tax)
_taxmode = 1
Case 1 ''!Normal_mode(Ex tax)
_taxmode = 0
End Select
Case 1
Select Case rxByte(4)
Case 0 ''Pls_changeprice
RaiseEvent Pls_changeprice()
Case 1
End Select
Case 253
Select Case rxByte(4)
Case 0 ''Buffer overflow
Status = "Tax rx:Buffer overflow"
End Select
Case 255
Select Case rxByte(4)
Case 0
Case 1 ''Command unknown
Status = "Tax rx:Command unknown"
Case 2 ''ERROR_CRC
Status = "Tax rx:ERROR or CRC error"
End Select
End Select
End If
End Sub
Private Sub TestEvent() Implements Itaxcomm.testevent
RaiseEvent Pls_changeprice()
End Sub
Private Sub sp_Disposed(sender As Object, e As EventArgs) Handles sp.Disposed
End Sub
Private Sub sp_ErrorReceived(sender As Object, e As SerialErrorReceivedEventArgs) Handles sp.ErrorReceived
Status = "TAX commerror:" & e.ToString
End Sub
Private Sub Taxstate() Implements Itaxcomm.TaxState
Dim txarray = New Byte() {&H16, &H6, &H63, &H1, &H72, &H54}
sptx(txarray)
End Sub
Public Sub Triggerstartbutton() Implements Itaxcomm.Triggerstartbutton
Dim txarray = New Byte() {&H16, &H6, &H63, &H4, &H77, &H54}
sptx(txarray)
End Sub
Public Sub ChangepriceOK() Implements Itaxcomm.ChangepriceOK
Dim txarray = New Byte() {&H16, &H6, &H63, &H2, &H71, &H54}
sptx(txarray)
End Sub
Public Sub Reset() Implements Itaxcomm.Reset
Dim txarray = New Byte() {&H16, &H6, &H63, &H3, &H70, &H54}
sptx(txarray)
End Sub
Private Sub statetimer_Elapsed(sender As Object, e As ElapsedEventArgs) Handles statetimer.Elapsed
If sp.IsOpen Then Taxstate()
End Sub
Private Sub sptx(a() As Byte)
Do Until sp.BytesToWrite = 0
Loop
sp.Write(a, 0, a.Count)
End Sub
Public Function open() As Integer Implements Itaxcomm.open
Try
sp.BaudRate = 9600
sp.DataBits = 8
sp.Handshake = IO.Ports.Handshake.None
sp.Parity = IO.Ports.Parity.None
sp.RtsEnable = True
sp.ReceivedBytesThreshold = 1
sp.StopBits = IO.Ports.StopBits.One
If _comport <> "" And Not sp.IsOpen Then
sp.PortName = _comport
sp.Open()
statetimer.Interval = 1000
statetimer.Enabled = True
Return 0
Else
Return 1
End If
Catch ex As Exception
Status = "Serialport open:" & Err.Description
Return 1
End Try
End Function
Public Function close() As Integer Implements Itaxcomm.close
Try
If sp.IsOpen Then sp.Close()
statetimer.Enabled = False
Return 0
Catch ex As Exception
Status = "Serialport close:" & Err.Description
Return 1
End Try
End Function
Public Sub New()
MyBase.New()
End Sub
End Class:
and here is my vb6 testapplication code:
Option Explicit
Private WithEvents tc As taxcomm.taxcomm
Private Sub Command1_Click()
On Error GoTo errhandler
tc.Triggerstartbutton
Exit Sub
errhandler:
Text1.Text = Err.Number & Err.Description
End Sub
Private Sub Command2_Click()
On Error GoTo errhandler
tc.Reset
Exit Sub
errhandler:
Text1.Text = Err.Number & Err.Description
End Sub
Private Sub Command3_Click()
tc.testevent
End Sub
Private Sub Form_Load()
On Error GoTo errhandler
Set tc = CreateObject("Taxcomm.taxcomm")
tc.commport = "COM5"
If tc.Open = 0 Then
MsgBox "Active"
Else
MsgBox "Not active"
tc.Close
End If
Exit Sub
errhandler:
MsgBox Err.Number & " " & Err.Description
Resume Next
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
tc.Close
End Sub
Private Sub Form_Terminate()
tc.Close
End Sub
Private Sub tc_Pls_changeprice()
MsgBox "test"
End Sub
Private Sub Timer1_Timer()
On Error GoTo errhandler
Text1.Text = tc.taxstatus
Exit Sub
errhandler:
Text1.Text = Err.Number & Err.Description
tc.Close
End Sub
The .net class and the vb6 testapplication compiles as it should, but it seems to be something wrong with the generation of the TLB(due to something wrong in my .net code) so the event doesn't fire, and/or the exposed event are not correctly registered inside VB6 IDE.
This was originally in a comment, but putting this here to make clear what the answer was:
Surprising as it may sound, I've found that VB6 has some limitations when dealing with underscores in method and event names when doing some more advanced COM component / COM interop type stuff. This was years ago, so I cannot recall what pain point I specifically hit. A bit of a longshot, but just for the heck of it, try to rename you event to avoid the underscore
I have an app that connects a Windows VPN (not OpenVPN) using the rasphone.exe interface. I can successfully establish the connection but It prompts for the password each time. Is there a way to get the interface to remember the password so that if the connection is lost the connection can automatically be re-established programatically? As a note when I start the process for rasphone.exe I'm getting exceptions when I try to pass more than 1 parameter to it. The only parameter I can successfully pass is the entry name, I can't add parameters like -d, -h, or -f.
Here is the code I have:
Imports System.Linq
Imports System.Net.NetworkInformation
Public Class clsVPN
Public Delegate Sub delPing()
Public Delegate Sub delConnect()
Public Delegate Sub delIdle()
Public Delegate Sub delDisconnect()
Public Delegate Sub delStatus(blnConnected As Boolean)
Public Event Ping As delPing
Public Event Con As delConnect
Public Event Discon As delDisconnect
Public Event Idle As delIdle
Public Event StatusChanged As delStatus
Public strRASPhone As String = "C:\WINDOWS\system32\rasphone.exe"
Public strIPAddress As String = ""
Public strVPNCon As String = ""
Public blnConnected As Boolean = False
Dim file As String = "C : \Users\Tom\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk"
Protected Sub OnStatusChanged(blnConnected As Boolean)
RaiseEvent StatusChanged(blnConnected)
End Sub
Protected Sub OnDisconnect()
RaiseEvent Discon()
End Sub
Protected Sub OnPing()
RaiseEvent Ping()
End Sub
Protected Sub OnIdle()
RaiseEvent Idle()
End Sub
Protected Sub OnConnect()
RaiseEvent Con()
End Sub
Public ReadOnly Property Connected() As Boolean
Get
Return blnConnected
End Get
End Property
Public Property ConName() As String
Get
Return strVPNCon
End Get
Set(strValue As String)
strVPNCon = strValue
End Set
End Property
Public Function Test() As Boolean
Dim blnSucceed As Boolean = False
OnPing()
Dim p As New Ping()
If p.Send(strIPAddress).Status = IPStatus.Success Then
blnSucceed = True
Else
blnSucceed = False
End If
p = Nothing
If blnSucceed <> blnConnected Then
blnConnected = blnSucceed
OnStatusChanged(blnConnected)
End If
OnIdle()
Return blnSucceed
End Function
Public Function Connect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-f " & file & " -d "
OnConnect()
'MessageBox.Show("strVPNCon = " )
'Process.Start(strRASPhone, Convert.ToString(" -f ") & file & Convert.ToString(" -d ") _
' & strVPNCon)
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(5000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function Disconnect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-h "
OnDisconnect()
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(8000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function CheckConnection() As Boolean
Dim niVPN As NetworkInterface() =
NetworkInterface.GetAllNetworkInterfaces
Dim blnExist As Boolean =
niVPN.AsEnumerable().Any(Function(x) x.Name = ConName)
If blnExist Then
'MessageBox.Show("VPN Exists")
Else
' MessageBox.Show("VPN Does Not Exist")
End If
Return blnExist
End Function
Public Sub ProcessExec(processarg As String, param As String, wait As Boolean)
' Start the child process.
Dim p As New ProcessStartInfo
' Redirect the output stream of the child process.
p.FileName = processarg
p.Arguments = param
p.UseShellExecute = True
p.WindowStyle = ProcessWindowStyle.Normal
Dim proc As Process = Process.Start(p)
' Do Not wait for the child process to exit before
' reading to the end of its redirected stream.
If wait = True Then
proc.WaitForExit()
End If
End Sub
End Class
I know this was asked more than one year before.
I suppose that the described problem is not caused of the Visual Basic code. The problem may be caused from the file rasphone.pbk. It is generally contained in
%APPDATA%\Microsoft\Network\Connections\Pbk
This file can be read with a text editor. There exist an option PreviewUserPw after [YOURVPNNAME]. The value 1 generates a prompting before dialing in.
Changing of this line to
PreviewUserPw=0
will help.
I am trying to run some vb.net code that indicates if i'm connected to the internet
If My.Computer.Network.IsAvailable Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If
This works fine if I'm connecting to a WiFi signal that doesn't require a login. If I connect to a public WiFi signal that I'm required to login/pay and I execute the code before completing this step it still tells me I'm connected (in theory yes but without paying/logging in I'm not)
Any ideas how set this up?
Thanks
You could check for an internet connection by trying to read Google.com:
Public Shared Function CheckForInternetConnection() As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead("http://www.google.com")
Return True
End Using
End Using
Catch
Return False
End Try
End Function
Taken from: Here
I use this
Public Function HaveInternetConnection() As Boolean
Try
Return My.Computer.Network.Ping("www.google.com")
Catch
Return False
End Try
End Function
I create this class to track internet connection changes. This class can check the stable internet connections also (stable means, that the connection not change during N second). The class raise events, if the connection changes.
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Runtime.InteropServices.ComTypes
Imports System.Text
Imports System.Collections.Generic
Imports System.Linq
Imports System.Net.NetworkInformation
Imports System.Net
Public Enum InternetConnectionState
Connected
Disconnected
End Enum
Public Class NetworkConnections
Implements IDisposable
Public Shared Property CheckHostName As String = "www.google.com"
Public Property ConnectionStableAfterSec As Integer = 10
Private MonitoringStarted As Boolean = False
Private StableCheckTimer As System.Threading.Timer
Private IsFirstCheck As Boolean = True
Private wConnectionIsStable As Boolean
Private PrevInternetConnectionState As InternetConnectionState = InternetConnectionState.Disconnected
Public Event InternetConnectionStateChanged(ByVal ConnectionState As InternetConnectionState)
Public Event InternetConnectionStableChanged(ByVal IsStable As Boolean, ByVal ConnectionState As InternetConnectionState)
Public Sub StartMonitoring()
If MonitoringStarted = False Then
AddHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
MonitoringStarted = True
NetworkAddressChanged(Me, Nothing)
End If
End Sub
Public Sub StopMonitoring()
If MonitoringStarted = True Then
Try
RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
Catch ex As Exception
End Try
MonitoringStarted = False
End If
End Sub
Public ReadOnly Property ConnectionIsStableNow As Boolean
Get
Return wConnectionIsStable
End Get
End Property
<DllImport("wininet.dll")> _
Private Shared Function InternetGetConnectedState(ByRef Description As Integer, ByVal ReservedValue As Integer) As Boolean
End Function
Private Shared Function IsInternetAvailable() As Boolean
Try
Dim ConnDesc As Integer
Dim conn As Boolean = InternetGetConnectedState(ConnDesc, 0)
Return conn
Catch
Return False
End Try
End Function
Private Shared Function IsInternetAvailableByDns() As Boolean
Try
Dim iheObj As IPHostEntry = Dns.GetHostEntry(CheckHostName)
Return True
Catch
Return False
End Try
End Function
Public Shared Function CheckInternetConnectionIsAvailable() As Boolean
Return IsInternetAvailable() And IsInternetAvailableByDns()
End Function
Private Sub NetworkAddressChanged(sender As Object, e As EventArgs)
wConnectionIsStable = False
StableCheckTimer = New System.Threading.Timer(AddressOf ElapsedAndStable, Nothing, New TimeSpan(0, 0, ConnectionStableAfterSec), New TimeSpan(1, 0, 0))
If IsFirstCheck Then
If CheckInternetConnectionIsAvailable() Then
PrevInternetConnectionState = InternetConnectionState.Connected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
Else
PrevInternetConnectionState = InternetConnectionState.Disconnected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
End If
IsFirstCheck = False
Else
If CheckInternetConnectionIsAvailable() Then
If PrevInternetConnectionState <> InternetConnectionState.Connected Then
PrevInternetConnectionState = InternetConnectionState.Connected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
End If
Else
If PrevInternetConnectionState <> InternetConnectionState.Disconnected Then
PrevInternetConnectionState = InternetConnectionState.Disconnected
RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
End If
End If
End If
End Sub
Private Sub ElapsedAndStable()
If wConnectionIsStable = False Then
wConnectionIsStable = True
Dim hasnet As Boolean = CheckInternetConnectionIsAvailable()
RaiseEvent InternetConnectionStableChanged(True, IIf(hasnet, InternetConnectionState.Connected, InternetConnectionState.Disconnected))
End If
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Try
RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
Catch ex As Exception
End Try
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Track changes on a form with 2 listbox. Important! The events are thread unsafe, that need to be handle with invoke method.
Imports System.Net.NetworkInformation
Imports System.Net
Public Class frmNetworkConnections
Private WithEvents conn As NetworkConnections
Delegate Sub AddToList1Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
Delegate Sub AddToList2Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New NetworkConnections
End Sub
Sub AddToList1(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
If Me.InvokeRequired = True Then
Dim d As New AddToList1Callback(AddressOf AddToList1)
Me.Invoke(d, ConnectionState, IsStable)
Else
ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
End If
End Sub
Sub AddToList2(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
If Me.InvokeRequired = True Then
Dim d As New AddToList2Callback(AddressOf AddToList2)
Me.Invoke(d, ConnectionState, IsStable)
Else
ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
ListBox2.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
End If
End Sub
Private Sub conn_InternetConnectionStableChanged(IsStable As Boolean, ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStableChanged
AddToList2(ConnectionState, IsStable)
End Sub
Private Sub conn_InternetConnectionStateChanged(ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStateChanged
AddToList1(ConnectionState, False)
End Sub
Private Sub btnStartMonitoring_Click(sender As Object, e As EventArgs) Handles btnStartMonitoring.Click
btnStopMonitoring.Enabled = True
btnStartMonitoring.Enabled = False
conn.StartMonitoring()
End Sub
Private Sub btnStopMonitoring_Click(sender As Object, e As EventArgs) Handles btnStopMonitoring.Click
btnStopMonitoring.Enabled = False
btnStartMonitoring.Enabled = True
conn.StopMonitoring()
End Sub
End Class
The result is:
I use the stable connection changes.
If you dont want to track changes, only check the connection, you can use the CheckInternetConnectionIsAvailable() shared function.
You could use the Ping class to try to reach a host in the Internet. In order not to wait too long, you should set a timeout when using Send.
A good way to check if the user is connected to the internet is
If My.Computer.Network.Ping("www.google.com") Then
MsgBox("Computer is connected to the internet.")
End If
You can also use this code, however it's slower
Public Shared Function CheckForInternetConnection() As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead("http://www.google.com")
Return True
End Using
End Using
Catch
Return False
End Try
End Function
***** Best *****
The best Code For it, it not make any bug or Any slow.
Button Or Timer .. Etc
Try
If My.Computer.Network.Ping("www.google.com") Then
Label1.Text = "Internet Founded"
End If
Catch ex As Exception
'' Else ''
Label1.Text = "No internet Acess"
End Try
At least hope you gave me that
"Question Answer", it the best solution .Thanks.
(you can try it out)
Try
Dim client = New Net.WebClient
client.OpenRead("http://www.google.com")
Label21.Text = "Internet : Connected"
Catch
Label21.Text = "Internet : Disconnected"
End Try
Use this code in vb.net 100% solved, you can use this code form loading.
I am using this code and is working very well:
Public Function IsConnectedToInternet() As Boolean
If My.Computer.Network.IsAvailable Then
Try
Dim IPHost As IPHostEntry = Dns.GetHostEntry("www.google.com")
Return True
Catch
Return False
End Try
Else
Return False
End If
End Function
My.Computer.Network.Ping gave me problems so I used this function
Public Function fVerificaConnessioneInternet() As Boolean
Dim objPing As New System.Net.NetworkInformation.Ping
Try
Return If(objPing.Send("www.google.it").Status = IPStatus.Success, True, False)
Catch
Return False
End Try
End Function
or you could use this, a little better function to use. this should help you out if you need a c# version
http://www.guideushow.com/code-snippet/function-to-check-if-you-can-connect-to-the-internet-vb-net-c/
Public Function IsConnectionAvailable() As Boolean
' Returns True if connection is available
' Replace www.yoursite.com with a site that
' is guaranteed to be online - perhaps your
' corporate site, or microsoft.com
Dim objUrl As New System.Uri("http://www.google.com/")
' Setup WebRequest
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
objWebReq.Proxy = Nothing
Dim objResp As System.Net.WebResponse
Try
' Attempt to get response and return True
objResp = objWebReq.GetResponse
objResp.Close()
objWebReq = Nothing
Return True
Catch ex As Exception
' Error, exit and return False
objResp.Close()
objWebReq = Nothing
Return False
End Try
End Function
how to find gsm modem com port using vb.net? i writing this code :
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM5")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CMGS=""+628988397877""" & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("SUCCESS" & vbCrLf & Chr(26)) 'SMS sending
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
but in this code :
Dim SMSEngine As New SMSCOMMS("COM5")
i need to know which com port that my modem gsm was connected, so i need code that can automatically find com port, can someone help me please?
thank you very much.
nb : i use visual basic 2012 (vb.net)
like others said, you will have to loop all ports and check whether you can connect use Rate/port to connect to the GSM modem. Here is a library, it is c#, but you can download the source code to see how it works.
http://www.scampers.org/steve/sms/libraries.htm
The only way to do this automatically without having to either select the COM port in your program interface or hard code the port number is to attempt to open all available COM ports, and send each one some kind of status command and listen (with a short timeout period) for a reply that only the GSM modem would return. Of course, this means you may send weird commands to other serial devices, if any, that are attached to the computer, but I'm guessing in your case it will be the only serial port with anything attached.
See here for the function to get the list of serial port names on the current computer.
Here's the Code to Find Attached modems and their Attributes in vb.net.
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_POTSModem")
ComboBox1.Items.Clear()
For Each queryObj As ManagementObject In searcher.Get()
If queryObj("Status") = "OK" Then
modems = queryObj("Description")
baud = queryObj("MaxBaudRateToSerialPort")
Port = queryObj("AttachedTo")
da.rows.add(1)
da.rows(incount).item(1)=Port
da.rows(incount).item(2)=baud
ComboBox1.Items.Add(modems)
ComboBox1.SelectedIndex = ComboBox1.FindString("Nokia")
If ComboBox1.SelectedItem = "" Then
ComboBox1.SelectedIndex = ComboBox1.FindString("Samsung")
If ComboBox1.SelectedItem = "" Then
ComboBox1.SelectedIndex = 0
End If
End If
End If
intcount+=1
Next
You need to add reference to the System.management assembly and also import the namespace system.management.