闲话少述,直接代码,然后给出一个示范;
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
Imports System.Text
'创建一个ping类,flag返回ping的结果
Public Class myping
Public ipstr As String
Public flag As Boolean = False
Public NoexitPing As Boolean = True
Public ThreadPing As Thread
Public waiteTime As Integer = 100
Public JoinFlag As Boolean = True
Public Sub New()
'SyncLock GetType(myping)
If NoexitPing = True Then
Try
ThreadPing = New Thread(AddressOf pingSingle)
ThreadPing.Priority = ThreadPriority.BelowNormal
Catch ex As Exception
End Try
End If
'End SyncLock
End Sub
Public Sub pingStart()
'SyncLock GetType(myping)
If NoexitPing = True Then
ThreadPing.Start()
If JoinFlag Then
ThreadPing.Join()
Else
Dim n As Integer = 0
Do While n < waiteTime And flag = False
n += 10
Thread.Sleep(10)
Loop
End If
Else
ThreadPing.Abort()
End If
'End SyncLock
End Sub
Public Sub pingAbort()
NoexitPing = False
Try
ThreadPing.Abort()
Catch ex As Exception
End Try
End Sub
Public Sub pingSingle() '指向ipstr的ping函数
If NoexitPing = False Then Exit Sub
Try
flag = My.Computer.Network.Ping(ipstr)
Catch ex As Exception
flag = False
End Try
End Sub
End Class
应用示范:测试192.168.0网段内所有机器
三个文本框,填上192 168 0,一个按钮执行搜索,一个listbox1显示搜索内容。
创建线程t,线程内调用委托
Private t As Thread
Private Delegate Sub 消息()
Private pingStr As String
Private myp As myping
Private num As Integer
Private Sub 显示结果()
Me.ListBox1.Items.Add(pingStr)
Me.ProgressBar1.Value = num
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Me.ListBox1.Items.Clear()
Me.ProgressBar1.Visible = True
Me.ProgressBar1.Maximum = 255
t = New Thread(AddressOf myping) '建立新的线程
t.Start() '启动线程
End Sub
'///////////////////myping是主程序
Private Sub myping()
Dim a As Integer = CInt(TextBox1.Text), b As Integer = CInt(TextBox2.Text), c As Integer = TextBox3.Text
Dim i As Integer
For i = 1 To 255
Try
myp = New myping
myp.ipstr = a.ToString & "." & b.ToString & "." & c.ToString & "." & i
myp.JoinFlag = False '默认是TRUE,等待线程结束,时间比较长
myp.pingStart()
pingStr = myp.ipstr & "..." & myp.flag.ToString '检测网络连通的方法
num = i
myp.pingAbort()
Dim dh As 消息 = New 消息(AddressOf 显示结果)
If Me.InvokeRequired = True Then Me.Invoke(dh)
dh = Nothing
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
t.Abort()
End Sub
本文介绍了一种使用VBA编写的网络探测工具,该工具能够扫描特定IP范围内的主机连通性,通过创建线程并利用Ping命令检测网络状态。文章详细展示了如何在VBA中实现多线程Ping操作,并提供了完整的代码示例,适用于快速查找局域网内活动设备。
729

被折叠的 条评论
为什么被折叠?



