예제 #1
0
        mitemFilePrint_Click(object sender, EventArgs e)
        {
            // Display dialog to select printer & port.
            PAGESETUPDLGSTRUCT psd;

            psd = new PAGESETUPDLGSTRUCT();
            PrintSetupDlg.InitDlgStruct(ref psd, hwndForm);
            int iErr = PrintSetupDlg.ShowDialog(ref psd);

            if (iErr == 0)
            {
                // Either error...
                string strErr = PrintSetupDlg.GetErrorString();
                if (strErr != "Ok")
                {
                    MessageBox.Show(strErr, "PrintGdi");
                }
                // ...Or user clicked <Cancel>
                return;
            }

            IntPtr hdcPrinter = IntPtr.Zero;
            IntPtr hfont      = IntPtr.Zero;
            IntPtr hfontOld   = IntPtr.Zero;

            try
            {
                // Connect to printer by creating a DC.
                hdcPrinter = Printing.CreatePrinterDC(ref psd);
                if (hdcPrinter != IntPtr.Zero)
                {
                    // Select font.
                    hfont = GdiFont.Create(tboxInput.Font.Name,
                                           (int)tboxInput.Font.Size, 0, hdcPrinter);
                    hfontOld = GdiGraphics.SelectObject(hdcPrinter, hfont);

                    // Print
                    PrintJob_Gdi.PrintText(tboxInput, hdcPrinter);
                }
                else
                {
                    throw new System.Exception();
                }
            }
            catch
            {
                MessageBox.Show("Error connecting to printer.", "PrintGdi");
            }
            finally
            {
                // Cleanup
                GdiGraphics.SelectObject(hdcPrinter, hfontOld);
                GdiGraphics.DeleteObject(hfont);
                Printing.DeleteDC(hdcPrinter);

                // Clean up resources associated with print dialog.
                PrintSetupDlg.Close(ref psd);
            }
        }