Como definir qual impressora é a impressora padrão de sistema

IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine Translation ou MT), não tendo sido portanto traduzido ou revisto por pessoas. A Microsoft possui artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais, com o objetivo de oferecer em português a totalidade dos artigos existentes na base de dados de suporte. No entanto, a tradução automática não é sempre perfeita, podendo conter erros de vocabulário, sintaxe ou gramática. A Microsoft não é responsável por incoerências, erros ou prejuízos ocorridos em decorrência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza atualizações freqüentes ao software de tradução automática (MT). Obrigado.

Clique aqui para ver a versão em Inglês deste artigo: 266767
Este artigo foi arquivado. É oferecido "como está" e não será mais atualizado.
Sumário
Este artigo mostra como programaticamente definir qual impressora é a impressora padrão de sistema. Nem todos os aplicativos ou componentes podem selecionar uma impressora específica para usar. Isso torna necessário para alterar a impressora padrão para o sistema para que o aplicativo ou componente usarão a impressora desejada.
Mais Informações
Observação : este código altera a impressora padrão para todo o sistema. Portanto, todos os aplicativos que não especificam uma impressora, até mesmo aplicativos que atualmente estão sendo executados, usam esse mesmo padrão. Por esse motivo, convém ter seu código, lembre-se o padrão anterior e, em seguida, defina-o novamente quando terminar o trabalho de impressão.

O exemplo de código a seguir fornece um meio para determinar quais impressoras estão disponíveis e designar um como a impressora padrão de sistema.

Exemplo passo a passo

  1. Inicie um novo projeto Standard EXE no Visual Basic. O Form1 é criado por padrão.
  2. Adicione um novo módulo para o projeto e insira o código a seguir:
    Public Const HWND_BROADCAST = &HFFFFPublic Const WM_WININICHANGE = &H1A' constants for DEVMODE structurePublic Const CCHDEVICENAME = 32Public Const CCHFORMNAME = 32' constants for DesiredAccess member of PRINTER_DEFAULTSPublic Const STANDARD_RIGHTS_REQUIRED = &HF0000Public Const PRINTER_ACCESS_ADMINISTER = &H4Public Const PRINTER_ACCESS_USE = &H8Public Const PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or _PRINTER_ACCESS_ADMINISTER Or PRINTER_ACCESS_USE)' constant that goes into PRINTER_INFO_5 Attributes member' to set it as defaultPublic Const PRINTER_ATTRIBUTE_DEFAULT = 4' Constant for OSVERSIONINFO.dwPlatformIdPublic Const VER_PLATFORM_WIN32_WINDOWS = 1Public Type OSVERSIONINFO    dwOSVersionInfoSize As Long    dwMajorVersion As Long    dwMinorVersion As Long    dwBuildNumber As Long    dwPlatformId As Long    szCSDVersion As String * 128End TypePublic Type DEVMODE     dmDeviceName As String * CCHDEVICENAME     dmSpecVersion As Integer     dmDriverVersion As Integer     dmSize As Integer     dmDriverExtra As Integer     dmFields As Long     dmOrientation As Integer     dmPaperSize As Integer     dmPaperLength As Integer     dmPaperWidth As Integer     dmScale As Integer     dmCopies As Integer     dmDefaultSource As Integer     dmPrintQuality As Integer     dmColor As Integer     dmDuplex As Integer     dmYResolution As Integer     dmTTOption As Integer     dmCollate As Integer     dmFormName As String * CCHFORMNAME     dmLogPixels As Integer     dmBitsPerPel As Long     dmPelsWidth As Long     dmPelsHeight As Long     dmDisplayFlags As Long     dmDisplayFrequency As Long     dmICMMethod As Long        ' // Windows 95 only     dmICMIntent As Long        ' // Windows 95 only     dmMediaType As Long        ' // Windows 95 only     dmDitherType As Long       ' // Windows 95 only     dmReserved1 As Long        ' // Windows 95 only     dmReserved2 As Long        ' // Windows 95 onlyEnd TypePublic Type PRINTER_INFO_5     pPrinterName As String     pPortName As String     Attributes As Long     DeviceNotSelectedTimeout As Long     TransmissionRetryTimeout As LongEnd TypePublic Type PRINTER_DEFAULTS     pDatatype As Long     pDevMode As Long     DesiredAccess As LongEnd TypeDeclare Function GetProfileString Lib "kernel32" _Alias "GetProfileStringA" _(ByVal lpAppName As String, _ByVal lpKeyName As String, _ByVal lpDefault As String, _ByVal lpReturnedString As String, _ByVal nSize As Long) As LongDeclare Function WriteProfileString Lib "kernel32" _Alias "WriteProfileStringA" _(ByVal lpszSection As String, _ByVal lpszKeyName As String, _ByVal lpszString As String) As LongDeclare Function SendMessage Lib "user32" _Alias "SendMessageA" _(ByVal hwnd As Long, _ByVal wMsg As Long, _ByVal wParam As Long, _lparam As String) As LongDeclare Function GetVersionExA Lib "kernel32" _(lpVersionInformation As OSVERSIONINFO) As IntegerPublic Declare Function OpenPrinter Lib "winspool.drv" _Alias "OpenPrinterA" _(ByVal pPrinterName As String, _phPrinter As Long, _pDefault As PRINTER_DEFAULTS) As LongPublic Declare Function SetPrinter Lib "winspool.drv" _Alias "SetPrinterA" _(ByVal hPrinter As Long, _ByVal Level As Long, _pPrinter As Any, _ByVal Command As Long) As LongPublic Declare Function GetPrinter Lib "winspool.drv" _Alias "GetPrinterA" _(ByVal hPrinter As Long, _ByVal Level As Long, _pPrinter As Any, _ByVal cbBuf As Long, _pcbNeeded As Long) As LongPublic Declare Function lstrcpy Lib "kernel32" _Alias "lstrcpyA" _(ByVal lpString1 As String, _ByVal lpString2 As Any) As LongPublic Declare Function ClosePrinter Lib "winspool.drv" _(ByVal hPrinter As Long) As Long    Public Sub SelectPrinter(NewPrinter As String)        Dim Prt As Printer                For Each Prt In Printers            If Prt.DeviceName = NewPrinter Then                Set Printer = Prt            Exit For            End If        Next    End Sub					
  3. Coloque um controle ListBox e um CommandButton no Form1.
  4. Adicione o seguinte código à seção General Declarations do Form1:
    Option ExplicitPrivate Function PtrCtoVbString(Add As Long) As String    Dim sTemp As String * 512, x As Long    x = lstrcpy(sTemp, Add)    If (InStr(1, sTemp, Chr(0)) = 0) Then         PtrCtoVbString = ""    Else         PtrCtoVbString = Left(sTemp, InStr(1, sTemp, Chr(0)) - 1)    End IfEnd FunctionPrivate Sub SetDefaultPrinter(ByVal PrinterName As String, _    ByVal DriverName As String, ByVal PrinterPort As String)    Dim DeviceLine As String    Dim r As Long    Dim l As Long    DeviceLine = PrinterName & "," & DriverName & "," & PrinterPort    ' Store the new printer information in the [WINDOWS] section of    ' the WIN.INI file for the DEVICE= item    r = WriteProfileString("windows", "Device", DeviceLine)    ' Cause all applications to reload the INI file:    l = SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows")End SubPrivate Sub Win95SetDefaultPrinter()    Dim Handle As Long          'handle to printer    Dim PrinterName As String    Dim pd As PRINTER_DEFAULTS    Dim x As Long    Dim need As Long            ' bytes needed    Dim pi5 As PRINTER_INFO_5   ' your PRINTER_INFO structure    Dim LastError As Long    ' determine which printer was selected    PrinterName = List1.List(List1.ListIndex)    ' none - exit    If PrinterName = "" Then        Exit Sub    End If    ' set the PRINTER_DEFAULTS members    pd.pDatatype = 0&    pd.DesiredAccess = PRINTER_ALL_ACCESS Or pd.DesiredAccess    ' Get a handle to the printer    x = OpenPrinter(PrinterName, Handle, pd)    ' failed the open    If x = False Then        'error handler code goes here        Exit Sub    End If    ' Make an initial call to GetPrinter, requesting Level 5    ' (PRINTER_INFO_5) information, to determine how many bytes    ' you need    x = GetPrinter(Handle, 5, ByVal 0&, 0, need)    ' don't want to check Err.LastDllError here - it's supposed    ' to fail    ' with a 122 - ERROR_INSUFFICIENT_BUFFER    ' redim t as large as you need    ReDim t((need \ 4)) As Long    ' and call GetPrinter for keepers this time    x = GetPrinter(Handle, 5, t(0), need, need)    ' failed the GetPrinter    If x = False Then        'error handler code goes here        Exit Sub    End If    ' set the members of the pi5 structure for use with SetPrinter.    ' PtrCtoVbString copies the memory pointed at by the two string    ' pointers contained in the t() array into a Visual Basic string.    ' The other three elements are just DWORDS (long integers) and    ' don't require any conversion    pi5.pPrinterName = PtrCtoVbString(t(0))    pi5.pPortName = PtrCtoVbString(t(1))    pi5.Attributes = t(2)    pi5.DeviceNotSelectedTimeout = t(3)    pi5.TransmissionRetryTimeout = t(4)    ' this is the critical flag that makes it the default printer    pi5.Attributes = PRINTER_ATTRIBUTE_DEFAULT       ' call SetPrinter to set it       X = SetPrinter(Handle, 5, pi5, 0)       If X = False Then   ' SetPrinter failed           MsgBox "SetPrinter Failed. Error code: " & Err.LastDllError           Exit Sub       Else           If Printer.DeviceName <> List1.Text Then           ' Make sure Printer object is set to the new printer                SelectPrinter (List1.Text)           End If       End If    ' and close the handle    ClosePrinter (Handle)End SubPrivate Sub GetDriverAndPort(ByVal Buffer As String, DriverName As _    String, PrinterPort As String)    Dim iDriver As Integer    Dim iPort As Integer    DriverName = ""    PrinterPort = ""    ' The driver name is first in the string terminated by a comma    iDriver = InStr(Buffer, ",")    If iDriver > 0 Then         ' Strip out the driver name        DriverName = Left(Buffer, iDriver - 1)        ' The port name is the second entry after the driver name        ' separated by commas.        iPort = InStr(iDriver + 1, Buffer, ",")        If iPort > 0 Then            ' Strip out the port name            PrinterPort = Mid(Buffer, iDriver + 1, _            iPort - iDriver - 1)        End If    End IfEnd SubPrivate Sub ParseList(lstCtl As Control, ByVal Buffer As String)    Dim i As Integer    Dim s As String    Do        i = InStr(Buffer, Chr(0))        If i > 0 Then            s = Left(Buffer, i - 1)            If Len(Trim(s)) Then lstCtl.AddItem s            Buffer = Mid(Buffer, i + 1)        Else            If Len(Trim(Buffer)) Then lstCtl.AddItem Buffer            Buffer = ""        End If    Loop While i > 0End SubPrivate Sub WinNTSetDefaultPrinter()    Dim Buffer As String    Dim DeviceName As String    Dim DriverName As String    Dim PrinterPort As String    Dim PrinterName As String    Dim r As Long    If List1.ListIndex > -1 Then        ' Get the printer information for the currently selected        ' printer in the list. The information is taken from the        ' WIN.INI file.        Buffer = Space(1024)        PrinterName = List1.Text        r = GetProfileString("PrinterPorts", PrinterName, "", _            Buffer, Len(Buffer))        ' Parse the driver name and port name out of the buffer        GetDriverAndPort Buffer, DriverName, PrinterPort           If DriverName <> "" And PrinterPort <> "" Then               SetDefaultPrinter List1.Text, DriverName, PrinterPort               If Printer.DeviceName <> List1.Text Then               ' Make sure Printer object is set to the new printer                  SelectPrinter (List1.Text)               End If           End If    End IfEnd SubPrivate Sub Command1_Click()    Dim osinfo As OSVERSIONINFO    Dim retvalue As Integer    osinfo.dwOSVersionInfoSize = 148    osinfo.szCSDVersion = Space$(128)    retvalue = GetVersionExA(osinfo)    If osinfo.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS Then        Call Win95SetDefaultPrinter    Else    ' This assumes that future versions of Windows use the NT method        Call WinNTSetDefaultPrinter    End IfEnd SubPrivate Sub Form_Load()    Dim r As Long    Dim Buffer As String    ' Get the list of available printers from WIN.INI    Buffer = Space(8192)    r = GetProfileString("PrinterPorts", vbNullString, "", _       Buffer, Len(Buffer))    ' Display the list of printer in the ListBox List1    ParseList List1, BufferEnd Sub					
  5. Executar o projeto e observe que o código anterior preenche uma ListBox com todas as impressoras disponíveis.
  6. Selecione uma impressora na lista e torne-o padrão clicando no CommandButton .
  7. Confirmar que a impressora padrão foi alterado: no botão Iniciar , selecione configurações , selecione Printers e verificar qual impressora está marcada como o padrão. Como alternativa, você pode imprimir na impressora padrão de qualquer aplicativo em seu sistema.
Referências
Para obter informações adicionais, clique nos números abaixo para ler os artigos na Base de dados de Conhecimento da Microsoft:
167735CORRECÇÃO: Falha de configuração de impressora para item na coleção impressoras
253612CORRECÇÃO: Printers Collection pode não conter todas as impressoras na pasta Impressoras
246772Como recuperar e definir a impressora padrão no Windows
global

Aviso: este artigo foi traduzido automaticamente

Propriedades

ID do Artigo: 266767 - Última Revisão: 12/05/2015 20:51:47 - Revisão: 3.3

Microsoft Visual Basic 4.0 Professional Edition, Microsoft Visual Basic 5.0 Professional Edition, Microsoft Visual Basic 6.0 Professional Edition, Microsoft Visual Basic 4.0 Enterprise Edition, Microsoft Visual Basic 5.0 Enterprise Edition, Microsoft Visual Basic Enterprise Edition for Windows 6.0, Microsoft Visual Basic 5.0 Learning Edition, Microsoft Visual Basic 6.0 Learning Edition

  • kbnosurvey kbarchive kbmt kbapi kbcodesnippet kbgdi kbhowto kbprint kbspooler KB266767 KbMtpt
Comentários