VB6 是否能够 "cast" 类型为 "Printer" 的对象?

Does VB6 have the ability to "cast" an object as type "Printer"?

Private Function SelectAPrinter(myName As String) As Printer

Dim strComputer As String
Dim objWMIService As Object
Dim myPrinter As Object

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

Set myPrinter = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")

Set SelectAPrinter = myPrinter
  
End Function

所以 VB6 当然会用“类型不匹配”对我咆哮,这不足为奇。我正在尝试设置一个对象 (myPrinter) 输入打印机。

我不知道如何完成这个功能。 是否有将对象“转换”为打印机类型的方法?

如果您不介意暂时设置默认打印机,那么下面的方法或许可行。


Option Explicit

Private Sub Command1_Click()
    Dim saveme As String
    Dim yourprinter As Printer
    
    saveme = Printer.DeviceName
    
    Set yourprinter = SelectAPrinter("Canon iR-ADV C5045/5051 PCL5c")
    
    Debug.Print "selected", yourprinter.DeviceName ' Microsoft Print to PDF
    
    Call SelectAPrinter(saveme) ' restore default
    
    Debug.Print "restored", Printer.DeviceName
End Sub

Private Function SelectAPrinter(myName As String) As Printer
    
    Dim strComputer As String
    Dim objWMIService As Object
    Dim colInstalledPrinters As Object
    Dim myPrinter As Object
    
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2")
    
    Set colInstalledPrinters = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")
    For Each myPrinter In colInstalledPrinters
        myPrinter.SetDefaultPrinter
        Exit For
    Next
    
    Set SelectAPrinter = Printer
      
End Function


您可以使用辅助方法将对象“投射”到打印机。但是,辅助方法确实使用了 Printers 集合:

Private Function SelectAPrinter(myName As String) As Printer
   Dim MyWMIService As Object
   Dim MyPrinters As Object
   Dim MyPrinter As Object
   
   Set MyWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\cimv2")
   Set MyPrinters = MyWMIService.ExecQuery("Select Name from Win32_Printer where Name = '" & myName & "'")
   
   For Each MyPrinter In MyPrinters
       Set SelectAPrinter = FindPrinter(MyPrinter.Name)
       Exit For
   Next
End Function

Private Function FindPrinter(ByVal DeviceName As String) As Printer
   Dim p As Printer
   
   For Each p In Printers
      If UCase(p.DeviceName) = UCase(DeviceName) Then
         Set FindPrinter = p
         Exit For
      End If
   Next
End Function