check if installed network printer is online
Asked Answered
T

1

6

I want to check if printer is online. For this I get the printer handle with OpenPrinter. Then I want to use PRINTER_STATUS_OFFLINE in PRINTER_INFO_6 with GetPrinter(). The result is always 0?

How do I get the offline state of my printer?

Code I used.

bool IsPrinterOnline(wstring strPrinterFriendlyName)
{
  HANDLE hPrinter ;
  if ( OpenPrinter(const_cast<LPWSTR>(strPrinterFriendlyName.c_str()), &hPrinter, NULL) == 0 )
  {    
    /*OpenPrinter call failed*/
    return false;
  }

  DWORD dwBufsize = 0;
  PRINTER_INFO_6* pinfo = 0;
  GetPrinter(hPrinter, 6,(LPBYTE)pinfo, dwBufsize, &dwBufsize); //Get dwBufsize

  PRINTER_INFO_6* pinfo6 = (PRINTER_INFO_6*)malloc(dwBufsize); //Allocate with dwBufsize
  GetPrinter(hPrinter, 6,(LPBYTE)pinfo6, dwBufsize, &dwBufsize);

  DWORD dwStatus = pinfo6->dwStatus; //always returns 0

  if (dwStatus == PRINTER_STATUS_OFFLINE)
  {
    free(pinfo6); 
    ClosePrinter( hPrinter );
    return false;
  }

  free(pinfo6); 
  ClosePrinter( hPrinter );
  return true;
}
Trever answered 19/10, 2012 at 9:15 Comment(2)
Are both GetPrinter actually succeed?Quoit
Second GetPrinter has succeeded (returned non-zero). But status is always zero.Trever
T
7

I fixed it. i used "pinfo2->Attributes & PRINTER_ATTRIBUTE_WORK_OFFLINE".

Here is the code.

bool IsPrinterOnline(wstring strPrinterFriendlyName)
{
  HANDLE hPrinter ;
  if ( OpenPrinter(const_cast<LPWSTR>(strPrinterFriendlyName.c_str()), &hPrinter, NULL) == 0 )
  {    
    /*OpenPrinter call failed*/
    return false;
  }

  DWORD dwBufsize = 0;
  PRINTER_INFO_2* pinfo = 0;
  int nRet = 0;
  nRet = GetPrinter(hPrinter, 2,(LPBYTE)pinfo, dwBufsize, &dwBufsize); //Get dwBufsize
  DWORD dwGetPrinter = 0;
  if (nRet == 0)
  {
    dwGetPrinter = GetLastError(); 
  }

  PRINTER_INFO_2* pinfo2 = (PRINTER_INFO_2*)malloc(dwBufsize); //Allocate with dwBufsize
  nRet = GetPrinter(hPrinter, 2,reinterpret_cast<LPBYTE>(pinfo2), dwBufsize, &dwBufsize);
  if (nRet == 0)
  {
    dwGetPrinter = GetLastError(); 
    return false;
  }

  if (pinfo2->Attributes & PRINTER_ATTRIBUTE_WORK_OFFLINE )
  {
    free(pinfo2); 
    ClosePrinter( hPrinter );
    return false;
  }

  free(pinfo2); 
  ClosePrinter( hPrinter );
  return true;
}
Trever answered 22/10, 2012 at 6:13 Comment(2)
@CristianAmarie: can you please explain your comment ?Flabby
A network printer can be reported as online while the physical device is actually offline. I'm not saying is always true, but that is happening. Also the reverse has happened: network printer reported on my computer as offline (which was false), and I could not print anything. I asked a colleague to print something and voila - the printer updated its status back to online. Most likely there is a disagreement between the spooler and the network list manager/UPnP/whatever mechanism Win32 is using.Yorick

© 2022 - 2024 — McMap. All rights reserved.