HOW TO:设置默认打印机

Author:水如烟  
需要引用System.Management空间再Imports System.Management
使用:

     Private   Sub  Button2_Click( ByVal  sender  As  System.Object,  ByVal  e  As  System.EventArgs)  Handles  Button2.Click
        
For   Each  printer  As   String   In  PrinterService.GetPrinterNames( " . " )
            Console.WriteLine(printer)
        
Next
    
End Sub

    
Private   Sub  Button3_Click( ByVal  sender  As  System.Object,  ByVal  e  As  System.EventArgs)  Handles  Button3.Click
        Console.WriteLine(PrinterService.SetDefaultPrinter(
" . " " EPSON LQ-1600KIII " ))
    
End Sub

 

Public   Class  PrinterService

    
Public   Shared   Function  GetPrinterNames( ByVal  computerName  As   String As   String ()
        
Dim  mResult( - 1 As   String

        
Dim  gManagementObject  As   New  ManagementObject
        gManagementObject.Scope 
=   New  ManagementScope( String .Format( " \\{0}\root\cimv2 " , computerName))
        
Dim  gSearcher  As   New  ManagementObjectSearcher( String .Format( " SELECT DeviceID FROM {0} " " Win32_Printer " ))
        gSearcher.Scope 
=  gManagementObject.Scope
        
Try
            
For   Each  mManagementObject  As  ManagementObject  In  gSearcher.Get()
                
ReDim   Preserve  mResult(mResult.Length)
                mResult(mResult.Length 
-   1 =  mManagementObject.Properties.Item( " DeviceID " ).Value
            
Next
        
Catch  ex  As  Exception
            Console.WriteLine(ex.Message)
        
Finally
            gSearcher.Dispose()
            gManagementObject.Dispose()
        
End   Try

        
Return  mResult
    
End Function

    
Public   Shared   Function  SetDefaultPrinter( ByVal  computerName  As   String ByVal  PrinterName  As   String As   Boolean
        
Dim  mResult  As   Boolean   =   False

        
Dim  gManagementObject  As   New  ManagementObject
        gManagementObject.Scope 
=   New  ManagementScope( String .Format( " \\{0}\root\cimv2 " , computerName))
        
Dim  gSearcher  As   New  ManagementObjectSearcher( String .Format( " SELECT DeviceID FROM {0} " " Win32_Printer " ))
        gSearcher.Scope 
=  gManagementObject.Scope
        
Try
            
For   Each  mManagementObject  As  ManagementObject  In  gSearcher.Get()
                
If  mManagementObject.Properties.Item( " DeviceID " ).Value.ToString.Equals(PrinterName)  Then
                    mManagementObject.InvokeMethod(
" SetDefaultPrinter " Nothing )
                    
Exit   For
                
End   If
            
Next

            mResult 
=   True
        
Catch  ex  As  Exception
            Console.WriteLine(ex.Message)
        
Finally
            gSearcher.Dispose()
            gManagementObject.Dispose()
        
End   Try

        
Return  mResult
    
End Function
End Class

你可能感兴趣的:(打印)