Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
Hi everyone,
I am new to C++ and working on my degree project,
I have run the following code to print hello world to the printer, but nothing is printing, only a blank page.
Whats wrong with the code?

C++
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow )
{
	PRINTDLG pd;

	memset( &pd, 0, sizeof( pd ) );

	pd.lStructSize = sizeof( pd );

	/* 
	 * get rid of PD_RETURNDEFAULT on the line below if you'd like to
	 * see the "Printer Settings" dialog!
	 *
	 */
	pd.Flags = PD_RETURNDEFAULT | PD_RETURNDC;

	// try to retrieve the printer DC
	if( !PrintDlg( &pd ) )
	{
		MessageBox( NULL, "PrintDlg( &pd ) failed!", "Fatal Error", MB_OK | MB_ICONERROR );

		return -1;
	}

	DOCINFO di;
	HDC hPrinter = pd.hDC;

	// initialization of the printing!
	memset( &di, 0, sizeof( di ) );
	di.cbSize = sizeof( di );
	StartDoc( hPrinter, &di );

		// start the first and only page
		StartPage( hPrinter );

		// uncomment the following line to print in colour! :)
		 SetTextColor( hPrinter, 0x0000FF );

		// write "Hello, World!" to the printer's DC
		TextOut( hPrinter, 100, 100, "Hello, World!", 13 );

		// finish the first page
		EndPage( hPrinter );

	// end this document and release the printer's DC
	EndDoc( hPrinter );
	DeleteDC( hPrinter );

	return 0;
}
Posted
Comments
Richard MacCutchan 12-Aug-12 11:34am    
I just tried this and it worked fine. Use your debugger to step through and check that nothing strange is happening.
wedagedara 12-Aug-12 21:03pm    
Yes the problem was "TextOut( hPrinter, 1000, 1000, "Hello, World!", 13 );"
I need to change 100 to 1000
Thanks a lot

1 solution

I just tried your code with a PDF printer and it worked correctly.

StartDoc[^] and StartPage[^] both have a return value that specifies success or failure.
You might want to check the returns values to see if they return success. Either code to check the return value or debug the program to see what is returned.

I would also skip the color printing for now by commenting out the line:
C++
SetTextColor( hPrinter, 0x0000FF );

You might also want to increase the print coordinates in case you are printing outside the margins of the page:
C++
TextOut( hPrinter, 1000, 1000, "Hello, World!", 13 );
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900