Jump to content
Fivewin Brasil

FUNCTION ISPRINT() Alguém testou


kapiaba

Recommended Posts

obrigado "crisvam" pela resposta... a função ISPRINT() também é nativa no harbour, o que precisamos saber é como colocar a ISPRINT.C (que também tem no harbour/core do Viktor) e como chamá-la.

E, tem mais, alguém já a testou e ela funciona mesmo?

Pois a questão é muito simples:

No clipper (16 bits) a gente usava um loop assim:

do while lastkey()<>27 .and. .not. isprinter()

Então, se as informações abaixo dessem algum resultado .F. esse do/while iria ficar por ali até o pressionamento do ESC. Vejam as diversas situações que aconteciam:

- SE existe impressora LPT instalada e ligada (on/line) : .T.

- SE existe impressora LPT instalada mas DESLIGADA: .F.

- se existe impressora LPT instalada, ligada, mas, sem cabo paralelo: .F.

- se existe impressora LPT instalada, ligada, com cabo, mas travada: .F.

Viram, como era simples de se verificar algum problema de impressão?

Agora no harbour não funciona assim:

Desde que exista a instalação da impressora, o resultado será sempre .T.

Então, para nós (programadores) se estivermos na frente do computador, é muito fácil de se descobrir por que, que a impressão não saiu...

agora para o leigo, o usuário, o BIOS, a coisa é feia... ele simplesmente não levanta "sua b****" da poltrona pra ver se a impressora está travada, desligada, ou sem cabo, ou sei lá, pois, o sistema (nosso aplicativo) mandou a impressão e ele (usuário) está aguardando a impressão...

ENTÃO, alguém conseguiu desvendar este mistério?

Nestes tópicos, estou também questionando... e é bom todos acessarem e virem as respostas:

http://www.pctoledo.com.br/forum/viewtopic.php?f=4&t=15518&p=104059#p104059

http://www.hmgforum.com/viewtopic.php?f=43&t=4400&start=160

google/fórum/harbour (inglês): https://groups.google.com/forum/#!topic/harbour-users/uphW9lXb17o

Abraços e bom dia a todos!

Link to comment
Share on other sites

Amiguinhos,


Será que dá pra conseguir algo com isto:


? "GetPrintDefault()",GetPrintDefault(),"GetPrinter()",GetPrinter()
do case
case GetPrintDefault()=0 .and. empty( GetPrinter() )
? "Nenhuma impressora esta instalada."
case GetPrintDefault()=0 .and. !empty( GetPrinter() )
? "Servico de Spool esta desativado ou nenhuma impressora como padrao."
case GetPrintDefault()<>0
//aPrinter := GetPrinters()
//for i = 1 to len(aPrinter)
// cPrinter := aPrinter[i]
// cPort := substr(cPrinter,at(",",cPrinter)+1,20)
// if MsgYesNO( "Colocar impressora " + cPrinter + " como padrao?" )
// //SetPrinter( substr(cPrinter,1,at(",",cPrinter)-1) )
// SetPrintDefault( substr(cPrinter,1,at(",",cPrinter)-1) )
// PrinterInit()
// //SetDefaultPrinter( substr(cPrinter,1,at(",",cPrinter)-1) )
// endif
//next
endcase

Link to comment
Share on other sites


#include "FiveWin.ch"

Function myChoosePrinter()

Local aPrinters, cPrinter := ''
Local nPrinter := 0

aPrinters := GetPrinters()

nPrinter := MsgList( aPrinters, "Selecione a Impressora" )

if nPrinter != nil .and. nPrinter > 0

cPrinter := aPrinters[ nPrinter ]

endif

// msginfo( cPrinter )

Return( cPrinter )


Link to comment
Share on other sites


Function Imprime(cArq,cPrint)
*******************************
*
*
Local oPrn, aPrn:=GetPrinters()
if empty(aPrn)
MsgInfo('Não há impressoras instaladas')
return .f.
endif
If cPrint == Nil
cPrint := GetDefaultPrinter()
EndIf

nRet := PrintFileRaw(cPrint,cArq,'Pedido')
if nRet < 1
cMsg := 'Erro Imprimindo: '
SWITCH nRet
CASE -1
cMsg += "Invalid parameters passed to function" ; EXIT
CASE -2
cMsg += "WinAPI OpenPrinter() call failed" ; EXIT
CASE -3
cMsg += "WinAPI StartDocPrinter() call failed" ; EXIT
CASE -4
cMsg += "WinAPI StartPagePrinter() call failed" ; EXIT
CASE -5
cMsg += "WinAPI malloc() of memory failed" ; EXIT
CASE -6
cMsg += "Arquivo " + cArq + " não Localizado" ; EXIT
END
MsgInfo(cMesg)
EndIf

Return .t.


Link to comment
Share on other sites


#Include "FiveWin.Ch"

Function main()

aArray := GetPrinters()

for i = 1 to len(aArray)

cPrinterName := substr( aArray[i], 1, at( ",", aArray[i])-1 )

? "A impressora " + cPrinterName, IsPrint( alltrim( cPrinterName ) )

next

Return nil

Function GetPrinters()

Local aPrinter := {}
Local cAllEntries
Local cEntry
Local nStart
Local cName
Local cPrn
Local cPort
Local nJ

cAllEntries := STRTRAN( GetProfString( "Devices" ), Chr( 0 ), CRLF )

For nStart := 1 To MlCount( cAllEntries )

cName := MemoLine( cAllEntries,,nStart)
cEntry := GetProfString( "Devices",cName,"")
nJ := 2

Do While ! Empty(cPort := StrToken(cEntry,nJ++,","))
Aadd(aPrinter,Trim(cName)+" , "+Trim(cPort))
EndDo

Next

Return(aPrinter)

function IsPrint( QuePrinter )

LOCAL nStatus

DEFAULT QuePrinter := "LPT1:"

nStatus := PrnStatus( QuePrinter )

if nStatus < 1 ; return "Impressora OK"
elseif nStatus = 1 ; return "Impressora Pausada"
elseif nStatus = 2 ; return "Impressora com Erro"
elseif nStatus = 4 ; return "Impressora Deletando"
elseif nStatus = 8 ; return "Impressora em Modo Bandeija"
elseif nStatus = 16 ; return "Impressora Sem Papel"
elseif nStatus = 32 ; return "Impressora em Modo Manual"
elseif nStatus = 64 ; return "Impressora com Problema no Papel"
elseif nStatus = 128 ; return "Impressora Off Line(Desligada)"
elseif nStatus = 256 ; return "Impressora com IO Ativo"
elseif nStatus = 512 ; return "Impressora Ocupada"
elseif nStatus = 1024 ; return "Impressora Imprimindo"
elseif nStatus = 2048 ; return "Impressora Memoria Lotada"
elseif nStatus = 4096 ; return "Impressora Nao Instalada"
elseif nStatus = 8192 ; return "Impressora Aguardando"
elseif nStatus = 16384 ; return "Impressora Processando"
elseif nStatus = 32768 ; return "Impressora Inicializando"
elseif nStatus = 65536 ; return "Impressora em Atencao"
elseif nStatus = 131072 ; return "Impressora Toner Baixo"
elseif nStatus = 262144 ; return "Impressora Sem Toner"
elseif nStatus = 524288 ; return "Impressora PAGE_PUNT"
elseif nStatus = 1048576 ; return "Impressora Intervencao do Usuario"
elseif nStatus = 2097152 ; return "Impressora Sem Memoria"
elseif nStatus = 4194304 ; return "Impressora Tampa Aberta"
elseif nStatus = 8388608 ; return "Impressora Servidor Desconhecido"
elseif nStatus = 16777217 ; return "Impressora POWER_SAVE"
endif

//-> Fim do Programa


Link to comment
Share on other sites

O xarbour tem a função, veja a sintaxe e o exemplo IsPrinter()

Determines if print output can be processed.

Syntax

IsPrinter( [<cPrinterName>] ) --> lIsPrinter

Arguments <cPrinterName> An optional character string holding the name of a particular printer driver. Return

The function returns .T. (true) when the operating system can process print output, otherwise .F. (false) is returned.

Description

The IsPrinter() function is used to test if an application can pass print output to the operating system. This is usually the case when a print spooler is active. IsPrinter() cannot detect, if a physical printer is ready to print, since this is monitored by the operating system.

If a character string holding a particular printer name is passed, IsPrinter() returns .T. (true) if this printer is installed.

Note: under CA-Clipper (DOS), IsPrinter() checked the readiness of a physical printer. This is not possible with xHarbour's IsPrinter() function due to differences between DOS and modern operating systems.

Info

See also: GetDefaultPrinter(), GetPrinters(), PCol(), PRow(), SET DEVICE, SET PRINTER, SetPrc() Category: Printer functions Source: rtl\isprint.c LIB: xhb.lib DLL: xhbdll.dll Example

// The example outlines possibilities of getting printer information

// different from CA-Clipper (DOS).

PROCEDURE Main

LOCAL aPrinter := GetPrinters()

? ValToPrg( aPrinter )

? GetDefaultPrinter()

? IsPrinter()

? IsPrinter( aPrinter[1] )

? IsPrinter( "HP LaserJet" )

RETURN

Link to comment
Share on other sites

O xarbour tem a função, veja a sintaxe e o exemplo

IsPrinter()

Determines if print output can be processed.

Syntax

IsPrinter( [<cPrinterName>] ) --> lIsPrinter

Arguments <cPrinterName> An optional character string holding the name of a particular printer driver. Return

The function returns .T. (true) when the operating system can process print output, otherwise .F. (false) is returned.

Description

The IsPrinter() function is used to test if an application can pass print output to the operating system. This is usually the case when a print spooler is active. IsPrinter() cannot detect, if a physical printer is ready to print, since this is monitored by the operating system.

If a character string holding a particular printer name is passed, IsPrinter() returns .T. (true) if this printer is installed.

Note: under CA-Clipper (DOS), IsPrinter() checked the readiness of a physical printer. This is not possible with xHarbour's IsPrinter() function due to differences between DOS and modern operating systems.

InfoSee also: GetDefaultPrinter(), GetPrinters(), PCol(), PRow(), SET DEVICE, SET PRINTER, SetPrc() Category: Printer functions Source: rtl\isprint.c LIB: xhb.lib DLL: xhbdll.dllExample

// The example outlines possibilities of getting printer information

// different from CA-Clipper (DOS).

PROCEDURE Main

LOCAL aPrinter := GetPrinters()

? ValToPrg( aPrinter )

? GetDefaultPrinter()

? IsPrinter()

? IsPrinter( aPrinter[1] )

? IsPrinter( "HP LaserJet" )

RETURN

Crisvam... Você testou isto em FOR WINDOWS? Em FOR DOS, não muda, pois o programa MODO CONSOLE usa CMD.EXE.

Link to comment
Share on other sites

Uma idéia:



#include "FiveWin.ch"

FUNCTION Main()

LOCAL cPrint, nRet, cMsg
LOCAL oPrn, aPrn := GetPrinters()
LOCAL cArq := "INFO.TXT"

do case
case GetPrintDefault()=0 .and. empty( GetPrinters() )

? "Nenhuma impressora esta instalada."

case GetPrintDefault()=0 .and. !empty( GetPrinters() )

? "Servico de Spool esta desativado ou nenhuma impressora como padrao."

case GetPrintDefault()<>0

if empty(aPrn)

MsgInfo('Não há impressoras instaladas')

return .f.

endif

If cPrint == Nil

cPrint := GetDefaultPrinter()

EndIf

// Quando a impressora e virtual(PDFMACHINE) nao vai para o spool?
nRet := PrintFileRaw( cPrint, cArq, 'Pedido' )

// ? nRet // = 1 Tem impressora

if nRet < 1

cMsg := 'Erro Imprimindo: '

SWITCH nRet

CASE -1

cMsg += "Parâmetros Inválidos Passados Para a Função. " ; EXIT

CASE -2

cMsg += "WinAPI OpenPrinter() chamada falhou... " ; EXIT

CASE -3

cMsg += "WinAPI StartDocPrinter() chamada falhou... " ; EXIT

CASE -4

cMsg += "WinAPI StartPage() da impressora chamada falhou" ; EXIT

CASE -5

cMsg += "Alocação WinAPI de memória falhou... " ; EXIT

CASE -6

cMsg += "Arquivo " + cArq + " não Localizado... " ; EXIT

END

ENDIF

MsgInfo( cMsg )

endcase

RETURN NIL


Link to comment
Share on other sites

Mais uma, muito boa...

#include "FiveWin.ch"
 
*****************
Function CHAMAIMP()
 
   LOCAL cPrinterName, cPrinterPort, cCopias
   LOCAL aPrn    := GetPrinters(.t.,.f.)
   LOCAL nResult := -1
   LOCAL cMsg    := ""
 
   PARA TAM,cARQ   // S=136 N=79
 
   cARQ := "\TESTE.TXT"
 
   IF TAM=Nil
      TAM="S"
   ENDIF
 
   If Empty(aPrn)
      OBRIGA11()
      Return
   EndIf
 
   IF !EMPTY(cARQ)
      cFILE := cARQ
   ELSE
      MsgInfo("Não foi possivel Gerar arquivo de impressão, Tente Novamente.","Aviso do Sistema")
      Return
   ENDIF
 
   nPrn:=New_PRINTSETUP( @cPrinterName, @cCopias )
   *nPrn:=PRINTSETUP( @cPrinterName, @cCopias )
 
   for i=1 to len(aPrn)
      IF aPrn[i,1] = cPrinterName
         cPrinterPort = aPrn[i,2]
         exit
      ENDIF
   next
 
   IF cPrinterPort#Nil
 
      IF SY_IsPrint( cPrinterName ) # "Impressora OK"  // teste usando função da fivewin
         MsgInfo(SY_IsPrint(cPrinterName),"Aviso do Sistema")
         Return
      ENDIF
 
      IF LEFT(UPPER(cPrinterPort),3)="LPT"
         nResult := PrintFileRaw( cPrinterName, cFile, "Impressao Pelo Sistema" )
         IF nResult = -1
            cMsg = "Parametros Invalido, Favor Tentar Novamente"
         ELSEIF nResult = -2
            cMsg = "Falha na chamada da Impressora, Favor Verificar a Impressora"
         ELSEIF nResult = -3
            cMsg = "Falha ao Iniciar Impressão, Favor Verificar a Impressora"
         ELSEIF nResult = -4
            cMsg = "Falha ao Iniciar a Primeira Pagina, Favor Verificar a Impressora"
         ELSEIF nResult = -5
            cMsg = "Falha de Memoria da Impressora, Favor Verificar a Impressora"
         ELSEIF nResult = -6
            cMsg = "Não foi Possivel localizar o arquivo de Impressão, Favor Tentar Novamente"
         ENDIF
         IF len(alltrim(cMsg)) > 1
            MsgInfo(cMsg,"Aviso do Sistema")
            Return
         ENDIF
      ELSE
         IF TAM="S"
            IF !EMPTY(cPrinterName)
               Imprime(cFILE,136,cPrinterName,cCopias)
            ENDIF
         ELSE
            IF !EMPTY(cPrinterName)
               Imprime(cFILE,80,cPrinterName,cCopias)
            ENDIF
         ENDIF
      ENDIF
   ENDIF
 
RETURN NIL
 
#pragma BEGINDUMP
#include "windows.h"
#include "hbapi.h"
 
HB_FUNC( NEW_PRINTSETUP )
   {
     PRINTDLG   pd;
        LPDEVNAMES lpDevNames;
        LPDEVMODE lpDevMode;
        HWND hwnd;
  LPSTR lpPrinterName;
 
      // setting the handle
 // hwnd =(HWND) hb_parnl(1);
 
        // Initialize PRINTDLG
  ZeroMemory(&pd, sizeof(pd));
 
  pd.lStructSize = sizeof(pd);
  pd.hwndOwner = GetActiveWindow();
  pd.hDevMode    = NULL;
  pd.hDevNames   = NULL;
  pd.Flags       = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC;
  pd.nCopies     = 1;
 
  if (PrintDlg(&pd)==TRUE)
  {
     lpDevMode = (LPDEVMODE) GlobalLock( pd.hDevMode );
     GlobalUnlock( pd.hDevMode );
 
     lpDevNames = (LPDEVNAMES) GlobalLock( pd.hDevNames );
     if( lpDevNames )
     {
        GlobalUnlock( pd.hDevNames );
        lpPrinterName = ( LPSTR ) lpDevNames + lpDevNames->wDeviceOffset;
        hb_storc( (LPSTR)lpPrinterName, 1 );
        hb_storni( lpDevMode->dmCopies, 2 );
        if (pd.hDevMode)
            GlobalFree( pd.hDevMode );
            if (pd.hDevNames)
                GlobalFree( pd.hDevNames );
     }
     else
        hb_retc( "" );
  }
  else
     hb_retc( "" );
   }
#pragma ENDDUMP
 
Function SY_IsPrint( QuePrinter )
 
   LOCAL eStatus
 
   DEFAULT QuePrinter := "LPT1:"
 
   eStatus := PrnStatus( QuePrinter )
 
   if     eStatus <        1 ; return "Impressora OK"
   elseif eStatus =        1 ; return "Impressora Pausada"
   elseif eStatus =        2 ; return "Impressora com Erro"
   elseif eStatus =        4 ; return "Impressora Deletando"
   elseif eStatus =        8 ; return "Impressora em Modo Bandeja"
   elseif eStatus =       16 ; return "Impressora Sem Papel"
   elseif eStatus =       32 ; return "Impressora em Modo Manual"
   elseif eStatus =       64 ; return "Impressora com Problema no Papel"
   elseif eStatus =      128 ; return "Impressora OffLine"
   elseif eStatus =      256 ; return "Impressora com IO Ativo"
   elseif eStatus =      512 ; return "Impressora Ocupada"
   elseif eStatus =     1024 ; return "Impressora Imprimindo"
   elseif eStatus =     2048 ; return "Impressora Memoria Lotada"
   elseif eStatus =     4096 ; return "Impressora Nao Instalada"
   elseif eStatus =     8192 ; return "Impressora Aguardando"
   elseif eStatus =    16384 ; return "Impressora Processando"
   elseif eStatus =    32768 ; return "Impressora Inicializando"
   elseif eStatus =    65536 ; return "Impressora em Atencao"
   elseif eStatus =   131072 ; return "Impressora Toner Baixo"
   elseif eStatus =   262144 ; return "Impressora Sem Toner"
   elseif eStatus =   524288 ; return "Impressora PAGE_PUNT"
   elseif eStatus =  1048576 ; return "Impressora Intervencao do Usuario"
   elseif eStatus =  2097152 ; return "Impressora Sem Memoria"
   elseif eStatus =  4194304 ; return "Impressora Tampa Aberta"
   elseif eStatus =  8388608 ; return "Impressora Servidor Desconhecido"
   elseif eStatus = 16777217 ; return "Impressora POWER_SAVE"
   endif
return nil
 
*****************
Function OBRIGA11
   *****************
   IF MsgYesNo("ATENÇÃO !!! Não foi possivel localizar Nenhuma impressora Instalada no Windows, Deseja Instalar uma Agora ?","Aviso do Sistema")
 
   Endif
 
Return(Nil)
 
**************************************************
Function Imprime( cArq, tamrel ,cPrinter, cCopias)
 
   **************************************************
   local cTexto, nLinhas, nA, cLinha, oBMP
 
   #ifdef __XHARBOUR__
       local oPrinter := win32prn():New(cPrinter)
   #else
       local oPrinter := win_prn():New(cPrinter)
   #endif
 
   TAMREL := 80
 
   cText := memoread( cArq )
   oPrinter:Landscape:= .F.
   oPrinter:FormType:= 9
   oprinter:SetPrintQuality(-1) // qualidade da impressão
   oPrinter:Copies:=cCopias
 
   IF !oPrinter:Create()
      MsgStop("ATENÇÃO !!! Não foi possivel Iniciar a Impressão, Favor Verificar se a Impressora esta Ligada.","Aviso do Sistema")
      return NIL
   else
      IF !oPrinter:StartDoc("Impressao Pelo Sistema ")
         MsgStop("ATENÇÃO !!! Não foi possivel Iniciar a Impressão, Favor Verificar a Impressora","Aviso do Sistema")
         Return NIL
      endif
 
      IF File("logo.bmp")  // se tiver o arquivo logo.bmp dentro da mesma pasta ele vai imprimir o logo primeiro
         #ifdef __XHARBOUR__
          oBMP:= Win32BMP():new()
         #else
          oBMP:= Win_BMP():new()
         #endif
         oBmp:loadFile( "logo.bmp" )
         oBmp:Draw( oPrinter,  { 15,15,60,60 } )
         aTamlog := 9
      else
         aTamlog := 2
      endif
 
      FOR TT=1 TO aTamlog
         oPrinter:newline()
      NEXT
      //oPrinter:CharSet( 255 )
 
      IF TAMREL=80
         oPrinter:setfont('Courier New',,12,,,,255) // Normal
         nLines2 := 85
      ELSE
         oPrinter:SetFont("Courier New",13,{3,-50},0,.F.,.F.) // Comprimida
         nLines2 := 150
      ENDIF
      oPrinter:Bold(0) // Normal
      *   oPrinter:newline() // Inicia nova linha
 
      nLines := mlcount( cText, nLines2 )
      for nA := 1 to nLines
         cLine := memoline( cText, nLines2, nA, 1, .F. )
         If Left(AllTrim(cLine),1)==Chr(12) //SALTO DA PAGINA
            oPrinter:NewPage()
            IF FILE("logo.bmp")  // se tiver o arquivo logo.bmp dentro da mesma pasta ele vai imprimir o logo primeiro
               #ifdef __XHARBOUR__
                oBMP:= Win32BMP():new()
               #else
                oBMP:= Win_BMP():new()
               #endif
               oBmp:loadFile( "logo.bmp" )
               oBmp:Draw( oPrinter,  { 15,15,60,60 } )
               aTamlog := 9
            else
               aTamlog := 2
            endif
         endif
 
         oPrinter:TextOut( cLine, .T. )
         oPrinter:Bold(0) // Normal
 
         if (oPrinter:MaxRow()-2 ) <= oPrinter:Prow()
            oPrinter:NewPage()
            IF FILE("logo.bmp")  // se tiver o arquivo logo.bmp dentro da mesma pasta ele vai imprimir o logo primeiro
               #ifdef __XHARBOUR__
                oBMP:= Win32BMP():new()
               #else
                oBMP:= Win_BMP():new()
               #endif
               oBmp:loadFile( "logo.BMP" )  // BMP
               oBmp:Draw( oPrinter,  { 15,15,60,60 } )
               aTamlog := 9
            else
               aTamlog := 2
            endif
 
            FOR TT=1 TO aTamlog
               oPrinter:newline()
            NEXT
         endif
      next
 
      oPrinter:EndDoc()
      oPrinter:Destroy()
 
   ENDIF
 
RETURN NIL
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...