前言:
转载请附上连接,本帖原创请勿照抄。
以前自己搜索MFC连接打印机程序之后总感觉花里胡哨看不懂,写半天都在出错。今天发布一篇关于MFC连接打印机的文章,希望可以帮助到大家{简化版通俗易懂(就算看不懂复制粘贴都能运行出来)}
环境VS2017,VS低版本可以复制粘贴高版本可以直接导入升级一下项目版本就可以。无需附加别的包。
1.新建BUT按钮实现函数
/**
*按钮函数主要实现初始化打印机
*/
void CprintDlg::OnBnClickedButton1()
{
CPrintDialog dlg(FALSE);
if (dlg.DoModal() == IDCANCEL)
return;
HDC hPrintDC = dlg.GetPrinterDC();
DOCINFO P_info;
::ZeroMemory(&P_info, sizeof(DOCINFO));
P_info.cbSize = sizeof(DOCINFO);
P_info.lpszDocName = "Print";
P_info.lpszOutput = NULL;
StartDoc(hPrintDC, &P_info);
LPDEVMODE Mode = dlg.GetDevMode();
int A4, B5;
if (Mode->dmPaperSize == DMPAPER_A4)//设置为A4纸
A4 = 1;
else
A4 = 0;
B5 = 0;//20070115
if (Mode->dmPaperSize == DMPAPER_B5 || Mode->dmPaperSize == DMPAPER_ENV_B5 || Mode->dmPaperSize == DMPAPER_EXECUTIVE)
{
B5 = 1;
}
else//20070115
{
B5 = 0;
}
if (1)
{
Mode->dmOrientation = DMORIENT_PORTRAIT;
ResetDC(hPrintDC, Mode);
}
else
{
Mode->dmOrientation = DMORIENT_LANDSCAPE;
ResetDC(hPrintDC, Mode);
}
int res = StartPage(hPrintDC);
SetMapMode(hPrintDC, MM_TWIPS);
//第一页
GoPrint(CDC::FromHandle(hPrintDC));
EndPage(hPrintDC);
EndDoc(hPrintDC);
DeleteDC(hPrintDC);
}
2.在源文件(.h)和实现文件(.cpp)初始化一个字体 以及初始化字体参数 位置参数
/**
*.h源文件
*/
public:
afx_msg void OnBnClickedButton1();
void GoPrint(CDC * pDC);
CFont* newFontTitle;//标题
bool IsA4;
bool IsB5;
int Top;
int Left;
};
/**
*.cpp文件
*/
#define UNIT 567
#define BLEN 0.65
void CprintDlg::GoPrint(CDC* pDC)
{
newFontTitle = new CFont;//标题
pDC->SetMapMode(MM_TWIPS);
pDC->SetBkMode(TRANSPARENT);
IsA4 = 1;
Top = 0;
Left = int(3 * UNIT);
IsB5 = 0;
if (IsA4 == 1)
{
Top = -150;
Left = 150;
}
else if (IsA4 == 0)
{
Top = -200;
Left = 100;
}
if (IsB5)
{
Top = 0;
Left = 0;
}
}
3.调用程序实现打印
/**
*实现打印功能
*/
newFontTitle->CreatePointFont(1300, "宋体");
CFont* oldFont = (CFont*)pDC->SelectObject(newFontTitle);
pDC->TextOut(4000, -800, "Dream.2017@qq.com MFC实现打印功能");
pDC->SelectObject(oldFont);
发帖不易,希望对你有所帮助。
完整版下载地址连接:https://download.csdn.net/download/qq_37529913/12311312