如何在VB6中获取打印机的IP地址

how to get the ip address of a printer in VB6

我想获取打印机的 IP 地址(通过 USB 连接到 PC)。

我目前使用的是 VB6。

您需要检查从 WMI 查询中检索到的打印机对象的 Port 属性。在下面的示例中,您可以从 WMI 查询中删除 WHERE 子句以获取所有已安装的打印机,然后您可以测试每台打印机上的端口。显然并非所有打印机都有 IP(XPS Document Writer 等...)

Sub Main()

  Debug.Print GetPrinterPort("HP Color LaserJet CP4005 PCL6")

End Sub

Function GetPrinterPort(printerName As String) As String

  Dim oWMI As Object
  Dim oPrinters As Object
  Dim oPrinter As Object
  Dim sPort As String

  sPort = ""

  Set oWMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\.\root\cimv2")

  Set oPrinters = oWMI.ExecQuery("Select * from Win32_Printer WHERE name = '" & printerName & "'")

  If Not oPrinters Is Nothing Then
    For Each oPrinter In oPrinters
      sPort = oPrinter.PortName
      Exit For
    Next
  End If

  Set oWMI = Nothing
  Set oPrinters = Nothing
  Set oPrinter = Nothing

  GetPrinterPort = sPort

End Function