Originally posted by ammar
See...
This is one of the "no answer" queston, I saw this question many times and no body ever answered it!
I think somebody should give the answer, and maybe it can be added to the FAQ's, because it's really very common.
You still cant find the answer!!?!! This has been answered so many times...do a search and you will find all sorts of info......but as its the season of goodwill....
CodeMonkey's example works fine for me on WinXP with a battered old cannon printer on LPT1........if you have a USB printern then I dont think it will work.....
There are various ways to do this, but if you are on windows then its best to do it properly and use the API (remember that these days there are often more than 1 printer and not all printers are on COM1 or LPT1 - there are network printers, Faxs...etc)......this code has a function that recieves a string and then opens the print dialog (that you all know) to chose which printer to send to (it can be USB...or even a fax...etc)....
Code:
#include <windows.h>
#include <commdlg.h>
#include <string>
#include <iostream>
//You must include comdlg32.lib for this to work
bool PrintIt(const std::string& str){
PRINTDLG pd = {0};
pd.lStructSize = sizeof(PRINTDLG);
pd.hwndOwner = HWND_DESKTOP;
pd.Flags = PD_RETURNDC;
pd.nCopies = 1;
DOCINFO di = {sizeof(DOCINFO),"Printed by C++!",0};
if(!PrintDlg(&pd))
return false;
if(StartDoc(pd.hDC,&di)>0 && StartPage(pd.hDC)>0){
TextOut(pd.hDC,10,10,str.c_str(),str.length());
EndPage(pd.hDC);
EndDoc(pd.hDC);
}
DeleteDC(pd.hDC);
return true;
}
int main(int argc, char* argv[])
{
if(PrintIt("Hello World"))
std::cout << "Printed!";
else std::cout << "Not Printed";
return 0;
}