Пример #1
0
        /// <summary>
        /// Add a form
        /// </summary>
        public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                const int PRINTER_ACCESS_USE        = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                //const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype     = null;
                defaults.pDevMode      = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
                {
                    try
                    {
                        DeleteForm(hPrinter, PaperName);
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags                = 0;
                        formInfo.pName                = PaperName;
                        formInfo.Size.width           = (int)(WidthInMm * 1000.0);
                        formInfo.Size.height          = (int)(HeightInMm * 1000.0);
                        formInfo.ImageableArea.left   = 0;
                        formInfo.ImageableArea.right  = formInfo.Size.width;
                        formInfo.ImageableArea.top    = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("Failed! Error code:{2}",
                                                    PaperName, PrinterName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        const int      DM_OUT_BUFFER = 2;
                        const int      DM_IN_BUFFER = 8;
                        structDevMode  devMode = new structDevMode();
                        IntPtr         hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;


                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                        {
                            throw new ApplicationException("Cannot get the size of the DEVMODE struct!");
                        }

                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("Cannot get the DEVMODE Struct!");
                        }

                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());


                        devMode.dmFields = 0x10000;

                        devMode.dmFormName = PaperName;

                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,
                                                  printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("Cannot set the orientation!");
                        }

                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                        {
                            throw new ApplicationException(" Call GetPrinter failed!");
                        }

                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                        {
                            throw new ApplicationException("Call GetPrinter failed!");
                        }

                        printerInfo          = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "Call GetPrinter failed!");
                        }

                        SendMessageTimeout(
                            new IntPtr(HWND_BROADCAST),
                            WM_SETTINGCHANGE,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            Printer.SendMessageTimeoutFlags.SMTO_NORMAL,
                            1000,
                            out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("Cannot open prnter {0}, Error Code: {1}",
                                            PrinterName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr        hDC      = CreateDC(null, PrinterName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE   = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH  = 0x00000008L;
                    pDevMode.dmFields      = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize   = 256;
                    pDevMode.dmPaperWidth  = (short)(WidthInMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }
Пример #2
0
 internal static extern bool AddForm(
  IntPtr phPrinter,
     [MarshalAs(UnmanagedType.I4)] int level,
  ref FormInfo1 form);
Пример #3
0
 internal static extern bool AddForm(
     IntPtr phPrinter,
     [MarshalAs(UnmanagedType.I4)] int level,
     ref FormInfo1 form);
Пример #4
0
        /**/
        /// <summary>
        /// 删除已经存在的自定义纸张
        /// </summary>
        /// <param name="PrinterName">打印机名称</param>
        /// <param name="PaperName">纸张名称</param>
        public static void DeleteCustomPaperSize(string PrinterName, string PaperName)
        {
            const int PRINTER_ACCESS_USE        = 0x00000008;
            const int PRINTER_ACCESS_ADMINISTER = 0x00000004;

            structPrinterDefaults defaults = new structPrinterDefaults();

            defaults.pDatatype     = null;
            defaults.pDevMode      = IntPtr.Zero;
            defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

            IntPtr hPrinter = IntPtr.Zero;

            //打开打印机
            if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
            {
                try
                {
                    DeleteForm(hPrinter, PaperName);
                    ClosePrinter(hPrinter);
                }
                catch
                {
                }
            }
        }

        #endregion  除已经存在的自定义纸张
        #region 指定的打印机设置以mm为单位的自定义纸张(Form)
        /**/
        /// <summary>
        /// 指定的打印机设置以mm为单位的自定义纸张(Form)
        /// </summary>
        /// <param name="PrinterName">打印机名称</param>
        /// <param name="PaperName">Form名称</param>
        /// <param name="WidthInMm">以mm为单位的宽度</param>
        /// <param name="HeightInMm">以mm为单位的高度</param>
        public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                const int             PRINTER_ACCESS_USE        = 0x00000008;
                const int             PRINTER_ACCESS_ADMINISTER = 0x00000004;
                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype     = null;
                defaults.pDevMode      = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;
                IntPtr hPrinter = IntPtr.Zero;
                //打开打印机
                if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
                {
                    try
                    {
                        //如果Form存在删除之
                        DeleteForm(hPrinter, PaperName);
                        //创建并初始化FORM_INFO_1
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags                = 0;
                        formInfo.pName                = PaperName;
                        formInfo.Size.width           = (int)(WidthInMm * 1000.0);
                        formInfo.Size.height          = (int)(HeightInMm * 1000.0);
                        formInfo.ImageableArea.left   = 0;
                        formInfo.ImageableArea.right  = formInfo.Size.width;
                        formInfo.ImageableArea.top    = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("向打印机 {1} 添加自定义纸张 {0} 失败!错误代号:{2}",
                                                    PaperName, PrinterName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        //初始化
                        const int      DM_OUT_BUFFER = 2;
                        const int      DM_IN_BUFFER = 8;
                        structDevMode  devMode = new structDevMode();
                        IntPtr         hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;


                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                        {
                            throw new ApplicationException("无法取得DEVMODE结构的大小!");
                        }

                        //分配缓冲
                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        //获取DEV_MODE指针
                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("无法获得DEVMODE结构!");
                        }

                        //填充DEV_MODE
                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());


                        devMode.dmFields = 0x10000;

                        //FORM名称
                        devMode.dmFormName = PaperName;

                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,
                                                  printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("无法为打印机设定打印方向!");
                        }

                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                        {
                            throw new ApplicationException("调用GetPrinter方法失败!");
                        }

                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                        {
                            throw new ApplicationException("调用GetPrinter方法失败!");
                        }

                        printerInfo          = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "调用SetPrinter方法失败,无法进行打印机设置!");
                        }

                        SendMessageTimeout(
                            new IntPtr(HWND_BROADCAST),
                            WM_SETTINGCHANGE,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            PrinterHelper_1.SendMessageTimeoutFlags.SMTO_NORMAL,
                            1000,
                            out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("无法打开打印机{0}, 错误代号: {1}",
                                            PrinterName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr        hDC      = CreateDC(null, PrinterName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE   = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH  = 0x00000008L;
                    pDevMode.dmFields      = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize   = 256;
                    pDevMode.dmPaperWidth  = (short)(WidthInMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Add a form
        /// </summary>
        public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                const int PRINTER_ACCESS_USE = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                //const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype = null;
                defaults.pDevMode = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
                {
                    try
                    {
                        DeleteForm(hPrinter, PaperName);
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags = 0;
                        formInfo.pName = PaperName;
                        formInfo.Size.width = (int)(WidthInMm * 1000.0);
                        formInfo.Size.height = (int)(HeightInMm * 1000.0);
                        formInfo.ImageableArea.left = 0;
                        formInfo.ImageableArea.right = formInfo.Size.width;
                        formInfo.ImageableArea.top = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("Failed! Error code:{2}",
                                PaperName, PrinterName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        const int DM_OUT_BUFFER = 2;
                        const int DM_IN_BUFFER = 8;
                        structDevMode devMode = new structDevMode();
                        IntPtr hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;

                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                            throw new ApplicationException("Cannot get the size of the DEVMODE struct!");

                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                            throw new ApplicationException("Cannot get the DEVMODE Struct!");

                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());

                        devMode.dmFields = 0x10000;

                        devMode.dmFormName = PaperName;

                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,
                                 printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                            throw new ApplicationException("Cannot set the orientation!");

                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                            throw new ApplicationException(" Call GetPrinter failed!");

                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                            throw new ApplicationException("Call GetPrinter failed!");

                        printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "Call GetPrinter failed!");

                        SendMessageTimeout(
                           new IntPtr(HWND_BROADCAST),
                           WM_SETTINGCHANGE,
                           IntPtr.Zero,
                           IntPtr.Zero,
                           Printer.SendMessageTimeoutFlags.SMTO_NORMAL,
                           1000,
                           out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("Cannot open prnter {0}, Error Code: {1}",
                        PrinterName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr hDC = CreateDC(null, PrinterName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH = 0x00000008L;
                    pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize = 256;
                    pDevMode.dmPaperWidth = (short)(WidthInMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Add the printer form to a printer 
        /// </summary>
        /// <param name="printerName">The printer name</param>
        /// <param name="paperName">Name of the printer form</param>
        /// <param name="widthMm">Width given in millimeters</param>
        /// <param name="heightMm">Height given in millimeters</param>
        public static void AddCustomPaperSize(string printerName, string paperName, float
         widthMm, float heightMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                // The code to add a custom paper size is different for Windows NT then it is
                // for previous versions of windows
                const int PRINTER_ACCESS_USE = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype = null;
                defaults.pDevMode = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;
                IntPtr hPrinter = IntPtr.Zero;
                // Open the printer.
                if (OpenPrinter(printerName, out hPrinter, ref defaults))
                {
                    try
                    {
                        // delete the form incase it already exists
                        DeleteForm(hPrinter, paperName);
                        // create and initialize the FORM_INFO_1 structure
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags = 0;
                        formInfo.pName = paperName;
                        // all sizes in 1000ths of millimeters
                        formInfo.Size.width = (int)(widthMm * 1000.0);
                        formInfo.Size.height = (int)(heightMm * 1000.0);
                        formInfo.ImageableArea.left = 0;
                        formInfo.ImageableArea.right = formInfo.Size.width;
                        formInfo.ImageableArea.top = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("Failed to add the custom paper size {0} to the printer {1}, System error number: {2}",
                             paperName, printerName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }
                        // INIT
                        const int DM_OUT_BUFFER = 2;
                        const int DM_IN_BUFFER = 8;
                        structDevMode devMode = new structDevMode();
                        IntPtr hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;

                        // GET THE SIZE OF THE DEV_MODE BUFFER
                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, printerName, IntPtr.Zero, IntPtr.Zero, 0);
                        if (iDevModeSize < 0)
                            throw new ApplicationException("Cannot get the size of the DEVMODE structure.");
                        // ALLOCATE THE BUFFER
                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);
                        // GET A POINTER TO THE DEV_MODE BUFFER
                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);
                        if (iRet < 0)
                            throw new ApplicationException("Cannot get the DEVMODE structure.");
                        // FILL THE DEV_MODE STRUCTURE
                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());
                        // SET THE FORM NAME FIELDS TO INDICATE THAT THIS FIELD WILL BE MODIFIED
                        devMode.dmFields = 0x10000; // DM_FORMNAME
                        // SET THE FORM NAME
                        devMode.dmFormName = paperName;
                        // PUT THE DEV_MODE STRUCTURE BACK INTO THE POINTER
                        Marshal.StructureToPtr(devMode, hDevMode, true);
                        // MERGE THE NEW CHAGES WITH THE OLD
                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName,
                                 printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);
                        if (iRet < 0)
                            throw new ApplicationException("Unable to set the orientation setting for this printer.");
                        // GET THE PRINTER INFO SIZE
                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                            throw new ApplicationException("GetPrinter failed. Couldn't get the # bytes needed for shared PRINTER_INFO_9 structure");
                        // ALLOCATE THE BUFFER
                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);
                        // GET A POINTER TO THE PRINTER INFO BUFFER
                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);
                        if (!bSuccess)
                            throw new ApplicationException("GetPrinter failed. Couldn't get the shared PRINTER_INFO_9 structure");
                        // FILL THE PRINTER INFO STRUCTURE
                        printerInfo = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;
                        // GET A POINTER TO THE PRINTER INFO STRUCTURE
                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);
                        // SET THE PRINTER SETTINGS
                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);
                        if (!bSuccess)
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "SetPrinter() failed.  Couldn't set the printer settings");
                        // Tell all open programs that this change occurred.
                        SendMessageTimeout(
                           new IntPtr(HWND_BROADCAST),
                           WM_SETTINGCHANGE,
                           IntPtr.Zero,
                           IntPtr.Zero,
                           MCCustomPrintForm.SendMessageTimeoutFlags.SMTO_NORMAL,
                           1000,
                           out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("Failed to open the {0} printer, System error number: {1}",
                     printerName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr hDC = CreateDC(null, printerName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH = 0x00000008L;
                    pDevMode.dmFields = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize = 256;
                    pDevMode.dmPaperWidth = (short)(widthMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(heightMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }
 /// <summary>
 /// Add the printer form to a printer
 /// </summary>
 /// <param name="printerName">The printer name</param>
 /// <param name="paperName">Name of the printer form</param>
 /// <param name="widthMm">Width given in millimeters</param>
 /// <param name="heightMm">Height given in millimeters</param>
 public void AddCustomPaperSize(string printerName, string paperName, float
                                width, float height)
 {
     if (PlatformID.Win32NT == Environment.OSVersion.Platform)
     {
         // The code to add a custom paper size is different for Windows NT then it is
         // for previous versions of windows
         structPrinterDefaults defaults = InitPrinterDefaults();
         IntPtr hPrinter = IntPtr.Zero;
         // Open the printer.
         if (OpenPrinter(printerName, out hPrinter, ref defaults))
         {
             try
             {
                 // delete the form incase it already exists
                 DeleteForm(hPrinter, paperName);
                 // create and initialize the FORM_INFO_1 structure
                 FormInfo1 formInfo = new FormInfo1();
                 formInfo.Flags = 0;
                 formInfo.pName = paperName;
                 // all sizes in 1000ths of millimeters
                 formInfo.Size.width           = (int)(width * 100.0);
                 formInfo.Size.height          = (int)(height * 100.0);
                 formInfo.ImageableArea.left   = 0;
                 formInfo.ImageableArea.right  = formInfo.Size.width;
                 formInfo.ImageableArea.top    = 0;
                 formInfo.ImageableArea.bottom = formInfo.Size.height;
                 if (!AddForm(hPrinter, 1, ref formInfo))
                 {
                     StringBuilder strBuilder = new StringBuilder();
                     strBuilder.AppendFormat(
                         "Failed to add the custom paper size {0} to the printer {1}, System error number: {2}",
                         paperName, printerName, GetLastError());
                     throw new ApplicationException(strBuilder.ToString());
                 }
                 else
                 {
                     SetForm(hPrinter, paperName, 1, ref formInfo);
                 }
                 SetPrinterDevMode(hPrinter, printerName, paperName);
             }
             finally
             {
                 ClosePrinter(hPrinter);
             }
         }
         else
         {
             StringBuilder strBuilder = new StringBuilder();
             strBuilder.AppendFormat("Failed to open the {0} printer, System error number: {1}",
                                     printerName, GetLastError());
             throw new ApplicationException(strBuilder.ToString());
         }
     }
     else
     {
         structDevMode pDevMode = new structDevMode();
         IntPtr        hDC      = CreateDC(null, printerName, null, ref pDevMode);
         if (hDC != IntPtr.Zero)
         {
             const long DM_PAPERSIZE   = 0x00000002L;
             const long DM_PAPERLENGTH = 0x00000004L;
             const long DM_PAPERWIDTH  = 0x00000008L;
             pDevMode.dmFields      = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
             pDevMode.dmPaperSize   = 256;
             pDevMode.dmPaperWidth  = (short)(width * 1000.0);
             pDevMode.dmPaperLength = (short)(height * 1000.0);
             ResetDC(hDC, ref pDevMode);
             DeleteDC(hDC);
         }
     }
 }
 internal static extern bool SetForm(IntPtr phPrinter, string paperName,
                                     [MarshalAs(UnmanagedType.I4)] int level, ref FormInfo1 form);
Пример #9
0
        public SetPrintPaper(string ReportName)
        {
            #region 设置自定义纸张格式,如果没有则添加,如果有则设为首选纸张
            //Add By Tany 2007-10-24
            //****************************************************************************************
            string _reportName = ReportName;
            int    _idx        = 0;
            //从_reportFilePath取出报表文件名
            //while (_reportName.IndexOf(@"\") >= 0)
            //{
            //    _idx = _reportName.IndexOf(@"\");
            //    _reportName = _reportName.Substring(_idx + 1);
            //}
            //_reportName = _reportName.Substring(0, _reportName.Length - 4);

            //查找数据库中设置的纸张格式
            string    sql     = "select * from jc_reportpaper where reportname='" + _reportName + "'";
            DataTable paperTb = TrasenFrame.Forms.FrmMdiMain.Database.GetDataTable(sql);
            //如果设置了纸张才进行下面的操作
            if (paperTb.Rows.Count > 0)
            {
                PrintDocument prtdoc            = new PrintDocument();
                string        strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;//获取默认打印机

                Microsoft.Win32.RegistryKey rk;
                if (!strDefaultPrinter.StartsWith(@"\\"))//本地打印机
                {
                    rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Printers\\" + strDefaultPrinter + "\\DsDriver");
                }
                else                                //网络打印机
                {
                    string[] p    = strDefaultPrinter.Remove(0, 2).Split(new char[] { '\\' });
                    string   path = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\LanMan Print Services\\Servers\\" + p[0] + "\\Printers\\" + p[1] + "\\DsDriver";
                    rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(path);
                }
                //获取默认打印机支持的纸张
                string[] papers    = (string[])(rk.GetValue("printMediaSupported"));
                int      iPaper    = 0;
                bool     Exist     = false;
                string   PaperName = paperTb.Rows[0]["PAPERNAME"].ToString();

                //查找这个纸张是否存在
                for (int i = 0; i < papers.Length; i++)
                {
                    if (papers[i].ToString().ToUpper() == PaperName.ToUpper())
                    {
                        iPaper = i;
                        Exist  = true;
                        break;
                    }
                }

                const int PRINTER_ACCESS_USE        = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype     = null;
                defaults.pDevMode      = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                //如果没有这个纸张则添加
                if (!Exist)
                {
                    //打开打印机
                    if (OpenPrinter(strDefaultPrinter, out hPrinter, ref defaults))
                    {
                        try
                        {
                            float WidthInMm  = Convert.ToSingle(paperTb.Rows[0]["PAPERWIDTH"]);
                            float HeightInMm = Convert.ToSingle(paperTb.Rows[0]["PAPERHEIGHT"]);

                            //创建并初始化FORM_INFO_1
                            FormInfo1 formInfo = new FormInfo1();
                            formInfo.Flags                = 0;
                            formInfo.pName                = PaperName;
                            formInfo.Size.width           = (int)(WidthInMm * 1000.0);
                            formInfo.Size.height          = (int)(HeightInMm * 1000.0);
                            formInfo.ImageableArea.left   = 0;
                            formInfo.ImageableArea.right  = formInfo.Size.width;
                            formInfo.ImageableArea.top    = 0;
                            formInfo.ImageableArea.bottom = formInfo.Size.height;
                            //AddForm(hPrinter, 1, ref formInfo);
                            if (!AddForm(hPrinter, 1, ref formInfo))
                            {
                                StringBuilder strBuilder = new StringBuilder();
                                strBuilder.AppendFormat("向打印机 {1} 添加自定义纸张 {0} 失败!错误代号:{2}",
                                                        PaperName, strDefaultPrinter, GetLastError());
                                throw new ApplicationException(strBuilder.ToString());
                            }
                            else
                            {
                                MessageBox.Show("自定义纸张已经设置成功,请重新打印!\n", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                //return false;
                            }
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(err.Message);
                        }
                        finally
                        {
                            ClosePrinter(hPrinter);
                        }
                    }
                }
                else//有纸张则设置为首选纸张
                {
                    //打开打印机
                    if (OpenPrinter(strDefaultPrinter, out hPrinter, ref defaults))
                    {
                        try
                        {
                            //初始化
                            const int      DM_OUT_BUFFER = 2;
                            const int      DM_IN_BUFFER = 8;
                            structDevMode  devMode = new structDevMode();
                            IntPtr         hPrinterInfo, hDummy;
                            PRINTER_INFO_9 printerInfo;
                            printerInfo.pDevMode = IntPtr.Zero;
                            int iPrinterInfoSize, iDummyInt;


                            int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, strDefaultPrinter, IntPtr.Zero, IntPtr.Zero, 0);

                            if (iDevModeSize < 0)
                            {
                                throw new ApplicationException("无法取得DEVMODE结构的大小!");
                            }

                            //分配缓冲
                            IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                            //获取DEV_MODE指针
                            int iRet = DocumentProperties(IntPtr.Zero, hPrinter, strDefaultPrinter, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                            if (iRet < 0)
                            {
                                throw new ApplicationException("无法获得DEVMODE结构!");
                            }

                            //填充DEV_MODE
                            devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());


                            devMode.dmFields = 0x10000;

                            //FORM名称
                            devMode.dmFormName = PaperName;

                            Marshal.StructureToPtr(devMode, hDevMode, true);

                            iRet = DocumentProperties(IntPtr.Zero, hPrinter, strDefaultPrinter,
                                                      printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                            if (iRet < 0)
                            {
                                throw new ApplicationException("无法为打印机设定打印方向!");
                            }

                            GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                            if (iPrinterInfoSize == 0)
                            {
                                throw new ApplicationException("调用GetPrinter方法失败!");
                            }

                            hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                            bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                            if (!bSuccess)
                            {
                                throw new ApplicationException("调用GetPrinter方法失败!");
                            }

                            printerInfo          = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                            printerInfo.pDevMode = hDevMode;

                            Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                            bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                            if (!bSuccess)
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error(), "调用SetPrinter方法失败,无法进行打印机设置!");
                            }

                            //SendMessageTimeout(
                            // new IntPtr(HWND_BROADCAST),
                            // WM_SETTINGCHANGE,
                            // IntPtr.Zero,
                            // IntPtr.Zero,
                            //SendMessageTimeoutFlags.SMTO_NORMAL,
                            // 1000,
                            // out hDummy);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(err.Message);
                        }
                        finally
                        {
                            ClosePrinter(hPrinter);
                        }
                    }
                }

                //PrintDocument doc = new PrintDocument();
                //int[] sizes = PaperSizeGetter.Get_PaperSizes(strDefaultPrinter);
                //int paperSizeid = sizes[iPaper];
                //string ss = doc.DefaultPageSettings.PaperSize.PaperName; doc.DefaultPageSettings.PaperSize.
                //rptDoc.PrintOptions.PaperSize = (CrystalDecisions.Shared.PaperSize)(paperSizeid);
                //int[] sizes = PaperSizeGetter.Get_PaperSizes(strDefaultPrinter);
                //int paperSizeid = sizes[iPaper];

                //ReportDocument rptDoc = new ReportDocument();
                //rptDoc.PrintOptions.PaperSize = (CrystalDecisions.Shared.PaperSize)(paperSizeid);

                //doc.DefaultPageSettings.PaperSize =rptDoc.PrintOptions.PaperSize;

                //PrintDocument doc = new PrintDocument();
            }
            //****************************************************************************************
            #endregion
        }
Пример #10
0
        /// <summary>
        /// Add the printer form to a printer
        /// </summary>
        /// <param name="printerName">The printer name</param>
        /// <param name="paperName">Name of the printer form</param>
        /// <param name="widthMm">Width given in millimeters</param>
        /// <param name="heightMm">Height given in millimeters</param>
        public static void AddCustomPaperSize(string printerName, string paperName, float
                                              widthMm, float heightMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                // The code to add a custom paper size is different for Windows NT then it is
                // for previous versions of windows

                const int PRINTER_ACCESS_USE        = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype     = null;
                defaults.pDevMode      = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                // Open the printer.
                if (OpenPrinter(printerName, out hPrinter, ref defaults))
                {
                    try
                    {
                        // delete the form incase it already exists
                        DeleteForm(hPrinter, paperName);
                        // create and initialize the FORM_INFO_1 structure
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags = 0;
                        formInfo.pName = paperName;
                        // all sizes in 1000ths of millimeters
                        formInfo.Size.width           = (int)(widthMm * 1000.0);
                        formInfo.Size.height          = (int)(heightMm * 1000.0);
                        formInfo.ImageableArea.left   = 0;
                        formInfo.ImageableArea.right  = formInfo.Size.width;
                        formInfo.ImageableArea.top    = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("Failed to add the custom paper size {0} to the printer {1}, System error number: {2}",
                                                    paperName, printerName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        // INIT
                        const int      DM_OUT_BUFFER = 2;
                        const int      DM_IN_BUFFER = 8;
                        structDevMode  devMode = new structDevMode();
                        IntPtr         hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;


                        // GET THE SIZE OF THE DEV_MODE BUFFER
                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, printerName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                        {
                            throw new ApplicationException("Cannot get the size of the DEVMODE structure.");
                        }

                        // ALLOCATE THE BUFFER
                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        // GET A POINTER TO THE DEV_MODE BUFFER
                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("Cannot get the DEVMODE structure.");
                        }

                        // FILL THE DEV_MODE STRUCTURE
                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());

                        // SET THE FORM NAME FIELDS TO INDICATE THAT THIS FIELD WILL BE MODIFIED
                        devMode.dmFields = 0x10000; // DM_FORMNAME
                        // SET THE FORM NAME
                        devMode.dmFormName = paperName;

                        // PUT THE DEV_MODE STRUCTURE BACK INTO THE POINTER
                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        // MERGE THE NEW CHAGES WITH THE OLD
                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, printerName,
                                                  printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("Unable to set the orientation setting for this printer.");
                        }

                        // GET THE PRINTER INFO SIZE
                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                        {
                            throw new ApplicationException("GetPrinter failed. Couldn't get the # bytes needed for shared PRINTER_INFO_9 structure");
                        }

                        // ALLOCATE THE BUFFER
                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        // GET A POINTER TO THE PRINTER INFO BUFFER
                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                        {
                            throw new ApplicationException("GetPrinter failed. Couldn't get the shared PRINTER_INFO_9 structure");
                        }

                        // FILL THE PRINTER INFO STRUCTURE
                        printerInfo          = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        // GET A POINTER TO THE PRINTER INFO STRUCTURE
                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        // SET THE PRINTER SETTINGS
                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "SetPrinter() failed.  Couldn't set the printer settings");
                        }

                        // Tell all open programs that this change occurred.
                        SendMessageTimeout(
                            new IntPtr(HWND_BROADCAST),
                            WM_SETTINGCHANGE,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            SendMessageTimeoutFlags.SMTO_NORMAL,
                            1000,
                            out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("Failed to open the {0} printer, System error number: {1}",
                                            printerName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr        hDC      = CreateDC(null, printerName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE   = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH  = 0x00000008L;
                    pDevMode.dmFields      = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize   = 256;
                    pDevMode.dmPaperWidth  = (short)(widthMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(heightMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }