Printer Name

Jul 18, 2008 at 4:41am
HI

I have written following code to get the default printer name

#include <windows.h>
#include <iostream.h>
#include <conio.h>
#include <winspool.h>
#define MAXPRINTERBUFFERSIZE 250
#define GETDEFAULTPRINTER "GetDefaultPrinterA"

using std::string;

string GetPrinterNameFunc();

int main()
{
string printerName = GetPrinterNameFunc();
cout<<printerName;
getch();
return 0;
}

typedef BOOL (*FNGETPRINTER)(LPTSTR ,DWORD );

string GetPrinterNameFunc()
{
BOOL bRet = FALSE ;
string strPrinterName;
// --- Load library winspool.drv ---
HMODULE hSpoolDrv = LoadLibrary("winspool.drv") ;


FNGETPRINTER fnGetPrinter = (FNGETPRINTER)GetProcAddress( hSpoolDrv, GETDEFAULTPRINTER ) ;

if( fnGetPrinter )
{
LPTSTR szPrinterName[MAX_PATH] ;
DWORD nLen = MAX_PATH ;

bRet = fnGetPrinter((LPTSTR)szPrinterName,nLen);

// --- Function call succeeds, then set the printer name ---
if( bRet )
strPrinterName = (char *)szPrinterName ;
}
FreeLibrary( hSpoolDrv ) ;
return strPrinterName;
}


I am using dev C++

Earlier it was working fine. But now I am getting error. When I open console window then I got an error message.



When I debug the program I am getting a message box saying

" An Access Violation(Segmentation Fault) raised in your program"

The error is coming on this line

"bRet = fnGetPrinter((LPTSTR)szPrinterName,nLen);"

Please advice

Regards
Karan
Last edited on Jul 18, 2008 at 4:46am
Jul 18, 2008 at 11:40am
You forgot to put an '&' in front of nLen when you call GetDefaultPrinterA().

If you plan to use the printer, you might as well just link to the DLL at compilation. Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <limits>
#include <string>

#define _WIN32_WINNT 0x0500
#include <windows.h>

std::string GetDefaultPrinterName()
  {
  char  result[ MAX_PATH ] = {'\0'};
  DWORD length             = MAX_PATH;
  GetDefaultPrinter( result, &length );
  return std::string( result );
  }

int main()
  {
  using namespace std;
  string printerName = GetDefaultPrinterName();
  cout << "The default printer is \"" << printerName << "\"\n";

  cout << "\n\nPress ENTER to quit.";
  cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
  return 0;
  }

The <limits> is for the numeric_limits template class.

The #define _WIN32_WINNT 0x0500 is to tell <windows.h> to prototype the GetDefaultPrinter() function.

Make sure to link with winspool when you compile. Using GCC at the command-line I wrote:
g++ -Wall -pedantic a.cpp -lwinspool

I'm sure that Dev-C++ has a menu option somewhere to specify what library files to link with.

This saves you having to manually load and unload the winspool DLL whenever you want to use the printer functions. Let the OS do it for you.

Hope this helps.
Topic archived. No new replies allowed.