将活动打印机更改为名称为 unknown/changing 的打印机

Change activeprinter to one with unknown/changing name

Visual Basic 应用程序版本 7.1

我愿意:

很容易找到可用打印机名称的列表,以及我正在搜索的 select(我使用了 Filter() 命令)。但是activeprinter还需要指定ne:端口号,我没找到

NE: 数字在每台计算机上都不同。您可以从注册表中读取。

Software\Microsoft\Windows NT\CurrentVersion\Devices

这是一个读取所有打印机名称的函数:

Global Const HKEY_CURRENT_USER = &H80000001
Global Const HKEY_LOCAL_MACHINE = &H80000002
Global Const KEY_READ = &H20019
Global Const REG_OPTION_NON_VOLATILE = &H0
Global Const strPrinterKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\Devices"

Declare PtrSafe Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" ( _
    ByVal hKey As LongPtr, ByVal lpSubKey As String, ByVal ulOptions As Long, _
    ByVal samDesired As Long, phkResult As LongPtr) As Long

Declare PtrSafe Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" ( _
    ByVal hKey As LongPtr, ByVal lpValueName As String, ByVal lpReserved As LongPtr, _
    lpType As Long, lpData As Any, lpcbData As Long) As Long

Declare PtrSafe Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As LongPtr) As Long

Public Sub DebugPrintAllPrinters()
    Dim oReg As Object, i As Long
    Dim strKeyPath As String, strValue As String, Msg As String
    Dim arrPrinter As Variant
    
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\default:StdRegProv")
    strKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\Devices"
    oReg.EnumValues HKEY_CURRENT_USER, strKeyPath, arrPrinter
    
    For i = 0 To UBound(arrPrinter)
        oReg.GetStringValue HKEY_CURRENT_USER, strKeyPath, arrPrinter(i), strValue
        Msg = Msg & arrPrinter(i) & Replace(strValue, "winspool,", " auf ") & vbCr
    Next
    
    Set oReg = Nothing
    Debug.Print Msg
End Sub

如果您知道打印机名称但不知道端口号,这里有一个设置打印机的简单方法。我们可以安全地假设我们打印机的端口号在 01 到 99 之间。因此,我们可以使用打印机名称和端口遍历所有可能的选项。当端口号不正确时,它会出错,我们只是在循环中恢复执行。对于端口号正确的一种情况,它将打印机设置为我们想要的打印机。

Function set_printer()
    
    Dim printer_string As String
    Dim port As Variant
    
    On Error Resume Next
    
    port = 0
    Do While port < 100
        If port < 10 Then
            ' add leading 0
            printer_string = "P3005 on Ne0" + CStr(port) + ":"
            Application.ActivePrinter = printer_string
        Else
            printer_string = "P3005 on Ne" + CStr(port) + ":"
            Application.ActivePrinter = printer_string
        End If
        port = port + 1
    Loop

End Function