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

时间:2015-08-18 06:22:16

标签: vb6 wmi

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

我目前正在使用VB6。

1 个答案:

答案 0 :(得分:1)

您需要检查从Port查询中检索的打印机对象的WMI属性。在下面的示例中,您可以从WHERE查询中删除WMI子句以获取所有已安装的打印机,然后您可以测试每台打印机上的端口。显然不是所有的打印机都有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