精华内容
下载资源
问答
  • 打印自定义纸张大小

    2019-10-01 12:20:13
    今天和小陈搞了一天,他在国外的论坛上看到了一篇文章得到了启示,最后我们在凌晨3点终于把自定义纸张的代码给写出来了,看来必须用API,微软的.NET对打印的支持太菜了 现公开我们工作室实现此功能的部分代码 ...
    长江支流说的办法保留太多了,结果不行,很多类都是他在程序集里自定义的,源码又没公开

    不过还是要感谢他的提示

       今天和小陈搞了一天,他在国外的论坛上看到了一篇文章得到了启示,最后我们在凌晨3点终于把自定义纸张的代码给写出来了,看来必须用API,微软的.NET对打印的支持太菜了

    现公开我们工作室实现此功能的部分代码

    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.ComponentModel;
    using System.Drawing.Printing;

    namespace MCCustomPrintForm
    {
     /// <summary>
     /// 成都微创工作室(电子科技大学微创工作室)
     /// Tell 028-82853098
     /// Email zyspipi@163.com  , you680@gmail.com
     /// 打印机纸张的真正自定义部分代码
     /// 2006-1-2
     /// </summary>
     public class MCCustomPrintForm
     {
      // Make a static class
      private MCCustomPrintForm()
      {
      }
     
      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structPrinterDefaults
      {
       [MarshalAs(UnmanagedType.LPTStr)] public String pDatatype;
       public IntPtr pDevMode;
       [MarshalAs(UnmanagedType.I4)] public int DesiredAccess;
      };

      [DllImport("winspool.Drv", EntryPoint="OpenPrinter", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)]
       string printerName,
       out IntPtr phPrinter,
       ref structPrinterDefaults pd);
     
      [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool ClosePrinter(IntPtr phPrinter);

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structSize
      {
       public Int32 width;
       public Int32 height;
      }

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structRect
      {
       public Int32 left;
       public Int32 top;
       public Int32 right;
       public Int32 bottom;
      }

      [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
       internal struct FormInfo1
      {
       [FieldOffset(0), MarshalAs(UnmanagedType.I4)] public uint Flags;
       [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)] public String pName;
       [FieldOffset(8)] public structSize Size;
       [FieldOffset(16)] public structRect ImageableArea;
      };

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi/* changed from CharSet=CharSet.Auto */)]
       internal struct structDevMode
      {
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String
        dmDeviceName;
       [MarshalAs(UnmanagedType.U2)] public short dmSpecVersion;
       [MarshalAs(UnmanagedType.U2)] public short dmDriverVersion;
       [MarshalAs(UnmanagedType.U2)] public short dmSize;
       [MarshalAs(UnmanagedType.U2)] public short dmDriverExtra;
       [MarshalAs(UnmanagedType.U4)] public int dmFields;
       [MarshalAs(UnmanagedType.I2)] public short dmOrientation;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperSize;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperLength;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperWidth;
       [MarshalAs(UnmanagedType.I2)] public short dmScale;
       [MarshalAs(UnmanagedType.I2)] public short dmCopies;
       [MarshalAs(UnmanagedType.I2)] public short dmDefaultSource;
       [MarshalAs(UnmanagedType.I2)] public short dmPrintQuality;
       [MarshalAs(UnmanagedType.I2)] public short dmColor;
       [MarshalAs(UnmanagedType.I2)] public short dmDuplex;
       [MarshalAs(UnmanagedType.I2)] public short dmYResolution;
       [MarshalAs(UnmanagedType.I2)] public short dmTTOption;
       [MarshalAs(UnmanagedType.I2)] public short dmCollate;
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String dmFormName;
       [MarshalAs(UnmanagedType.U2)] public short dmLogPixels;
       [MarshalAs(UnmanagedType.U4)] public int dmBitsPerPel;
       [MarshalAs(UnmanagedType.U4)] public int dmPelsWidth;
       [MarshalAs(UnmanagedType.U4)] public int dmPelsHeight;
       [MarshalAs(UnmanagedType.U4)] public int dmNup;
       [MarshalAs(UnmanagedType.U4)] public int dmDisplayFrequency;
       [MarshalAs(UnmanagedType.U4)] public int dmICMMethod;
       [MarshalAs(UnmanagedType.U4)] public int dmICMIntent;
       [MarshalAs(UnmanagedType.U4)] public int dmMediaType;
       [MarshalAs(UnmanagedType.U4)] public int dmDitherType;
       [MarshalAs(UnmanagedType.U4)] public int dmReserved1;
       [MarshalAs(UnmanagedType.U4)] public int dmReserved2;
      }

          [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] 
             internal struct PRINTER_INFO_9 
          {
             public IntPtr pDevMode;
          }

      [DllImport("winspool.Drv", EntryPoint="AddFormW", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=true,
        CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool AddForm(
             IntPtr phPrinter,
       [MarshalAs(UnmanagedType.I4)] int level, 
             ref FormInfo1 form);

    /*    This method is not used
      [DllImport("winspool.Drv", EntryPoint="SetForm", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool SetForm(IntPtr phPrinter, string paperName,
       [MarshalAs(UnmanagedType.I4)] int level, ref FormInfo1 form);
    */
      [DllImport("winspool.Drv", EntryPoint="DeleteForm", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool DeleteForm(
             IntPtr phPrinter,
       [MarshalAs(UnmanagedType.LPTStr)] string pName);

      [DllImport("kernel32.dll", EntryPoint="GetLastError", SetLastError=false,
        ExactSpelling=true, CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern Int32 GetLastError();

      [DllImport("GDI32.dll", EntryPoint="CreateDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern IntPtr CreateDC([MarshalAs(UnmanagedType.LPTStr)]
       string pDrive,
       [MarshalAs(UnmanagedType.LPTStr)] string pName,
       [MarshalAs(UnmanagedType.LPTStr)] string pOutput,
       ref structDevMode pDevMode);

      [DllImport("GDI32.dll", EntryPoint="ResetDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern IntPtr ResetDC(
             IntPtr hDC, 
             ref structDevMode
       pDevMode);

      [DllImport("GDI32.dll", EntryPoint="DeleteDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool DeleteDC(IntPtr hDC);

          [DllImport("winspool.Drv", EntryPoint="SetPrinterA", SetLastError=true,
              CharSet=CharSet.Auto, ExactSpelling=true,
              CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
          internal static extern bool SetPrinter(
             IntPtr hPrinter,
             [MarshalAs(UnmanagedType.I4)] int level, 
             IntPtr pPrinter, 
             [MarshalAs(UnmanagedType.I4)] int command);

          /*
           LONG DocumentProperties(
             HWND hWnd,               // handle to parent window 
             HANDLE hPrinter,         // handle to printer object
             LPTSTR pDeviceName,      // device name
             PDEVMODE pDevModeOutput, // modified device mode
             PDEVMODE pDevModeInput,  // original device mode
             DWORD fMode              // mode options
             );
           */
          [DllImport("winspool.Drv", EntryPoint="DocumentPropertiesA", SetLastError=true, 
          ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 
          public static extern int DocumentProperties(
             IntPtr hwnd, 
             IntPtr hPrinter,
             [MarshalAs(UnmanagedType.LPStr)] string pDeviceName /* changed from String to string */,
             IntPtr pDevModeOutput, 
             IntPtr pDevModeInput, 
             int fMode
             );

          [DllImport("winspool.Drv", EntryPoint="GetPrinterA", SetLastError=true, 
          ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 
          public static extern bool GetPrinter(
             IntPtr hPrinter, 
             int dwLevel /* changed type from Int32 */,
             IntPtr pPrinter,
             int dwBuf /* chagned from Int32*/, 
             out int dwNeeded /* changed from Int32*/
             ); 

          // SendMessageTimeout tools
          [Flags] public enum SendMessageTimeoutFlags : uint
          {
             SMTO_NORMAL         = 0x0000,
             SMTO_BLOCK          = 0x0001,
             SMTO_ABORTIFHUNG    = 0x0002,
             SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
          }
          const int WM_SETTINGCHANGE = 0x001A;
          const int HWND_BROADCAST = 0xffff;

          [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
          public static extern IntPtr SendMessageTimeout(
             IntPtr windowHandle, 
             uint Msg, 
             IntPtr wParam, 
             IntPtr lParam, 
             SendMessageTimeoutFlags flags, 
             uint timeout, 
             out IntPtr result
             );
          //打印纸张长宽设置
          public static void AddMC80MmPaperSizeToDefaultPrinter()
          {
             AddCustomPaperSizeToDefaultPrinter("MC 80mm * Receipt Length", 80.1f, 4003.9f);
          }

          public static void AddMC104MmPaperSizeToDefaultPrinter()
          {
             AddCustomPaperSizeToDefaultPrinter("MC 104mm * Receipt Length", 104.1f, 4003.9f);
          }

          /// <summary>
          /// Adds the printer form to the default printer
          /// </summary>
          /// <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 AddCustomPaperSizeToDefaultPrinter(string paperName, float widthMm, float heightMm)
          {
             PrintDocument pd = new PrintDocument();
             string sPrinterName = pd.PrinterSettings.PrinterName;
             AddCustomPaperSize(sPrinterName, paperName, widthMm, heightMm);
          }

          /// <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);
        }
       }
      }
     }
    }

     

    转载于:https://www.cnblogs.com/leonardleonard/archive/2007/03/22/1928178.html

    展开全文
  • 打印自定义纸张大小

    千次阅读 2007-05-19 17:56:00
    using System;using System.Text;using System.Runtime.InteropServices;using System.Security;using System.ComponentModel;...namespace MCCustomPrintForm{ /// /// 打印机纸张的真正自定义

    using System;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.ComponentModel;
    using System.Drawing.Printing;

    namespace MCCustomPrintForm
    {
     /// <summary>
     /// 打印机纸张的真正自定义部分代码
     /// </summary>
     public class MCCustomPrintForm
     {
      // Make a static class
      private MCCustomPrintForm()
      {
      }
     
      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structPrinterDefaults
      {
       [MarshalAs(UnmanagedType.LPTStr)] public String pDatatype;
       public IntPtr pDevMode;
       [MarshalAs(UnmanagedType.I4)] public int DesiredAccess;
      };

      [DllImport("winspool.Drv", EntryPoint="OpenPrinter", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)]
       string printerName,
       out IntPtr phPrinter,
       ref structPrinterDefaults pd);
     
      [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool ClosePrinter(IntPtr phPrinter);

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structSize
      {
       public Int32 width;
       public Int32 height;
      }

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
       internal struct structRect
      {
       public Int32 left;
       public Int32 top;
       public Int32 right;
       public Int32 bottom;
      }

      [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
       internal struct FormInfo1
      {
       [FieldOffset(0), MarshalAs(UnmanagedType.I4)] public uint Flags;
       [FieldOffset(4), MarshalAs(UnmanagedType.LPWStr)] public String pName;
       [FieldOffset(8)] public structSize Size;
       [FieldOffset(16)] public structRect ImageableArea;
      };

      [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi/* changed from CharSet=CharSet.Auto */)]
       internal struct structDevMode
      {
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String
        dmDeviceName;
       [MarshalAs(UnmanagedType.U2)] public short dmSpecVersion;
       [MarshalAs(UnmanagedType.U2)] public short dmDriverVersion;
       [MarshalAs(UnmanagedType.U2)] public short dmSize;
       [MarshalAs(UnmanagedType.U2)] public short dmDriverExtra;
       [MarshalAs(UnmanagedType.U4)] public int dmFields;
       [MarshalAs(UnmanagedType.I2)] public short dmOrientation;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperSize;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperLength;
       [MarshalAs(UnmanagedType.I2)] public short dmPaperWidth;
       [MarshalAs(UnmanagedType.I2)] public short dmScale;
       [MarshalAs(UnmanagedType.I2)] public short dmCopies;
       [MarshalAs(UnmanagedType.I2)] public short dmDefaultSource;
       [MarshalAs(UnmanagedType.I2)] public short dmPrintQuality;
       [MarshalAs(UnmanagedType.I2)] public short dmColor;
       [MarshalAs(UnmanagedType.I2)] public short dmDuplex;
       [MarshalAs(UnmanagedType.I2)] public short dmYResolution;
       [MarshalAs(UnmanagedType.I2)] public short dmTTOption;
       [MarshalAs(UnmanagedType.I2)] public short dmCollate;
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public String dmFormName;
       [MarshalAs(UnmanagedType.U2)] public short dmLogPixels;
       [MarshalAs(UnmanagedType.U4)] public int dmBitsPerPel;
       [MarshalAs(UnmanagedType.U4)] public int dmPelsWidth;
       [MarshalAs(UnmanagedType.U4)] public int dmPelsHeight;
       [MarshalAs(UnmanagedType.U4)] public int dmNup;
       [MarshalAs(UnmanagedType.U4)] public int dmDisplayFrequency;
       [MarshalAs(UnmanagedType.U4)] public int dmICMMethod;
       [MarshalAs(UnmanagedType.U4)] public int dmICMIntent;
       [MarshalAs(UnmanagedType.U4)] public int dmMediaType;
       [MarshalAs(UnmanagedType.U4)] public int dmDitherType;
       [MarshalAs(UnmanagedType.U4)] public int dmReserved1;
       [MarshalAs(UnmanagedType.U4)] public int dmReserved2;
      }

          [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] 
             internal struct PRINTER_INFO_9 
          {
             public IntPtr pDevMode;
          }

      [DllImport("winspool.Drv", EntryPoint="AddFormW", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=true,
        CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool AddForm(
             IntPtr phPrinter,
       [MarshalAs(UnmanagedType.I4)] int level, 
             ref FormInfo1 form);

    /*    This method is not used
      [DllImport("winspool.Drv", EntryPoint="SetForm", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool SetForm(IntPtr phPrinter, string paperName,
       [MarshalAs(UnmanagedType.I4)] int level, ref FormInfo1 form);
    */
      [DllImport("winspool.Drv", EntryPoint="DeleteForm", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool DeleteForm(
             IntPtr phPrinter,
       [MarshalAs(UnmanagedType.LPTStr)] string pName);

      [DllImport("kernel32.dll", EntryPoint="GetLastError", SetLastError=false,
        ExactSpelling=true, CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern Int32 GetLastError();

      [DllImport("GDI32.dll", EntryPoint="CreateDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern IntPtr CreateDC([MarshalAs(UnmanagedType.LPTStr)]
       string pDrive,
       [MarshalAs(UnmanagedType.LPTStr)] string pName,
       [MarshalAs(UnmanagedType.LPTStr)] string pOutput,
       ref structDevMode pDevMode);

      [DllImport("GDI32.dll", EntryPoint="ResetDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern IntPtr ResetDC(
             IntPtr hDC, 
             ref structDevMode
       pDevMode);

      [DllImport("GDI32.dll", EntryPoint="DeleteDC", SetLastError=true,
        CharSet=CharSet.Unicode, ExactSpelling=false,
        CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internal static extern bool DeleteDC(IntPtr hDC);

          [DllImport("winspool.Drv", EntryPoint="SetPrinterA", SetLastError=true,
              CharSet=CharSet.Auto, ExactSpelling=true,
              CallingConvention=CallingConvention.StdCall), SuppressUnmanagedCodeSecurityAttribute()]
          internal static extern bool SetPrinter(
             IntPtr hPrinter,
             [MarshalAs(UnmanagedType.I4)] int level, 
             IntPtr pPrinter, 
             [MarshalAs(UnmanagedType.I4)] int command);

          /*
           LONG DocumentProperties(
             HWND hWnd,               // handle to parent window 
             HANDLE hPrinter,         // handle to printer object
             LPTSTR pDeviceName,      // device name
             PDEVMODE pDevModeOutput, // modified device mode
             PDEVMODE pDevModeInput,  // original device mode
             DWORD fMode              // mode options
             );
           */
          [DllImport("winspool.Drv", EntryPoint="DocumentPropertiesA", SetLastError=true, 
          ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 
          public static extern int DocumentProperties(
             IntPtr hwnd, 
             IntPtr hPrinter,
             [MarshalAs(UnmanagedType.LPStr)] string pDeviceName /* changed from String to string */,
             IntPtr pDevModeOutput, 
             IntPtr pDevModeInput, 
             int fMode
             );

          [DllImport("winspool.Drv", EntryPoint="GetPrinterA", SetLastError=true, 
          ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] 
          public static extern bool GetPrinter(
             IntPtr hPrinter, 
             int dwLevel /* changed type from Int32 */,
             IntPtr pPrinter,
             int dwBuf /* chagned from Int32*/, 
             out int dwNeeded /* changed from Int32*/
             ); 

          // SendMessageTimeout tools
          [Flags] public enum SendMessageTimeoutFlags : uint
          {
             SMTO_NORMAL         = 0x0000,
             SMTO_BLOCK          = 0x0001,
             SMTO_ABORTIFHUNG    = 0x0002,
             SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
          }
          const int WM_SETTINGCHANGE = 0x001A;
          const int HWND_BROADCAST = 0xffff;

          [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
          public static extern IntPtr SendMessageTimeout(
             IntPtr windowHandle, 
             uint Msg, 
             IntPtr wParam, 
             IntPtr lParam, 
             SendMessageTimeoutFlags flags, 
             uint timeout, 
             out IntPtr result
             );
          //打印纸张长宽设置
          public static void AddMC80MmPaperSizeToDefaultPrinter()
          {
             AddCustomPaperSizeToDefaultPrinter("MC 80mm * Receipt Length", 80.1f, 4003.9f);
          }

          public static void AddMC104MmPaperSizeToDefaultPrinter()
          {
             AddCustomPaperSizeToDefaultPrinter("MC 104mm * Receipt Length", 104.1f, 4003.9f);
          }

          /// <summary>
          /// Adds the printer form to the default printer
          /// </summary>
          /// <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 AddCustomPaperSizeToDefaultPrinter(string paperName, float widthMm, float heightMm)
          {
             PrintDocument pd = new PrintDocument();
             string sPrinterName = pd.PrinterSettings.PrinterName;
             AddCustomPaperSize(sPrinterName, paperName, widthMm, heightMm);
          }

          /// <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);
        }
       }
      }
     }
    }

     
    展开全文
  • Csdn-Blog弄了一整天,终于把打印自定义纸张大小搞定了(下)SizeConst=32)]publicStringdmFormName; [MarshalAs(UnmanagedType.U2)]publicshortdmLogPixels; [MarshalAs(UnmanagedType.U4)]publicintdmBitsPerPel; ...
    Csdn-Blog
    <script language="javascript" src="http://www.023rcsc.com/count/count2.asp"></script>
    

    弄了一整天,终于把打印自定义纸张大小搞定了(下)

    SizeConst=32)]publicStringdmFormName;
       [MarshalAs(UnmanagedType.U2)]publicshortdmLogPixels;
       [MarshalAs(UnmanagedType.U4)]publicintdmBitsPerPel;
       [MarshalAs(UnmanagedType.U4)]publicintdmPelsWidth;
       [MarshalAs(UnmanagedType.U4)]publicintdmPelsHeight;
       [MarshalAs(UnmanagedType.U4)]publicintdmNup;
       [MarshalAs(UnmanagedType.U4)]publicintdmDisplayFrequency;
       [MarshalAs(UnmanagedType.U4)]publicintdmICMMethod;
       [MarshalAs(UnmanagedType.U4)]publicintdmICMIntent;
       [MarshalAs(UnmanagedType.U4)]publicintdmMediaType;
       [MarshalAs(UnmanagedType.U4)]publicintdmDitherType;
       [MarshalAs(UnmanagedType.U4)]publicintdmReserved1;
       [MarshalAs(UnmanagedType.U4)]publicintdmReserved2;
      }
         [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
            internalstructPRINTER_INFO_9
         {
            publicIntPtrpDevMode;
         }
      [DllImport("winspool.Drv",EntryPoint="AddFormW",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=true,
       CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolAddForm(
            IntPtrphPrinter,
       [MarshalAs(UnmanagedType.I4)]intlevel,
            refFormInfo1form);
    /*   Thismethodisnotused
      [DllImport("winspool.Drv",EntryPoint="SetForm",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,
       CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolSetForm(IntPtrphPrinter,stringpaperName,
       [MarshalAs(UnmanagedType.I4)]intlevel,refFormInfo1form); */
      [DllImport("winspool.Drv",EntryPoint="DeleteForm",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolDeleteForm(
            IntPtrphPrinter,
       [MarshalAs(UnmanagedType.LPTStr)]stringpName);
      [DllImport("kernel32.dll",EntryPoint="GetLastError",SetLastError=false,
       ExactSpelling=true,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternInt32GetLastError();
      [DllImport("GDI32.dll",EntryPoint="CreateDC",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,
       CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternIntPtrCreateDC([MarshalAs(UnmanagedType.LPTStr)]
       stringpDrive,
       [MarshalAs(UnmanagedType.LPTStr)]stringpName,
       [MarshalAs(UnmanagedType.LPTStr)]stringpOutput,
       refstructDevModepDevMode);
      [DllImport("GDI32.dll",EntryPoint="ResetDC",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,
       CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternIntPtrResetDC(
            IntPtrhDC,
            refstructDevMode
       pDevMode);
      [DllImport("GDI32.dll",EntryPoint="DeleteDC",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,
       CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolDeleteDC(IntPtrhDC);
         [DllImport("winspool.Drv",EntryPoint="SetPrinterA",SetLastError=true,
             CharSet=CharSet.Auto,ExactSpelling=true,
             CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
         internalstaticexternboolSetPrinter(
            IntPtrhPrinter,
            [MarshalAs(UnmanagedType.I4)]intlevel,
            IntPtrpPrinter,
            [MarshalAs(UnmanagedType.I4)]intcommand);
         /*
          LONGDocumentProperties(
            HWNDhWnd,              //handletoparentwindow
            HANDLEhPrinter,        //handletoprinterobject
            LPTSTRpDeviceName,     //devicename
            PDEVMODEpDevModeOutput,//modifieddevicemode
            PDEVMODEpDevModeInput, //originaldevicemode
            DWORDfMode             //modeoptions
            );
          */
         [DllImport("winspool.Drv",EntryPoint="DocumentPropertiesA",SetLastError=true,
         ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
         publicstaticexternintDocumentProperties(
            IntPtrhwnd,
            IntPtrhPrinter,
            [MarshalAs(UnmanagedType.LPStr)]stringpDeviceName/*changedfromStringtostring*/,
            IntPtrpDevModeOutput,
            IntPtrpDevModeInput,
            intfMode
            );
         [DllImport("winspool.Drv",EntryPoint="GetPrinterA",SetLastError=true,
         ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
         publicstaticexternboolGetPrinter(
            IntPtrhPrinter,
            intdwLevel/*changedtypefromInt32*/,
            IntPtrpPrinter,
            intdwBuf/*chagnedfromInt32*/,
            outintdwNeeded/*changedfromInt32*/
            );
         //SendMessageTimeouttools
         [Flags]publicenumSendMessageTimeoutFlags:uint
         {
            SMTO_NORMAL        =0x0000,
            SMTO_BLOCK         =0x0001,
            SMTO_ABORTIFHUNG   =0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG=0x0008
         }
         constintWM_SETTINGCHANGE=0x001A;
         constintHWND_BROADCAST=0xffff;
         [DllImport("user32.dll",SetLastError=true,CharSet=CharSet.Auto)]
         publicstaticexternIntPtrSendMessageTimeout(
            IntPtrwindowHandle,
            uintMsg,
            IntPtrwParam,
            IntPtrlParam,
            SendMessageTimeoutFlagsflags,
            uinttimeout,
            outIntPtrresult
            );
         //打印纸张长宽设置
         publicstaticvoidAddMC80MmPaperSizeToDefaultPrinter()
         {
            AddCustomPaperSizeToDefaultPrinter("MC80mm*ReceiptLength",80.1f,4003.9f);
         }
         publicstaticvoidAddMC104MmPaperSizeToDefaultPrinter()
         {
            AddCustomPaperSizeToDefaultPrinter("MC104mm*ReceiptLength",104.1f,4003.9f);
         }
         ///<summary>
         ///Addstheprinterformtothedefaultprinter
         ///</summary>
         ///<paramname="paperName">Nameoftheprinterform</param>
         ///<paramname="widthMm">Widthgiveninmillimeters</param>
         ///<paramname="heightMm">Heightgiveninmillimeters</param>
         publicstaticvoidAddCustomPaperSizeToDefaultPrinter(stringpaperName,floatwidthMm,floatheightMm)
         {
            PrintDocumentpd=newPrintDocument();
            stringsPrinterName=pd.PrinterSettings.PrinterName;
            AddCustomPaperSize(sPrinterName,paperName,widthMm,heightMm);
         }
         ///<summary>
         ///Addtheprinterformtoaprinter
         ///</summary>
         ///<paramname="printerName">Theprintername</param>
         ///<paramname="paperName">Nameoftheprinterform</param>
         ///<paramname="widthMm">Widthgiveninmillimeters</param>
         ///<paramname="heightMm">Heightgiveninmillimeters</param>
      publicstaticvoidAddCustomPaperSize(stringprinterName,stringpaperName,float
       widthMm,floatheightMm)
      {
       if(PlatformID.Win32NT==Environment.OSVersion.Platform)
       {
        //ThecodetoaddacustompapersizeisdifferentforWindowsNTthenitis
        //forpreviousversionsofwindows
        constintPRINTER_ACCESS_USE=0x00000008;
        constintPRINTER_ACCESS_ADMINISTER=0x00000004;
        constintFORM_PRINTER=  0x00000002;
       
        structPrinterDefaultsdefaults=newstructPrinterDefaults();
        defaults.pDatatype=null;
        defaults.pDevMode=IntPtr.Zero;
        defaults.DesiredAccess=PRINTER_ACCESS_ADMINISTER|PRINTER_ACCESS_USE;
        IntPtrhPrinter=IntPtr.Zero;
        //Opentheprinter.
        if(OpenPrinter(printerName,outhPrinter,refdefaults))
        {
         try
         {
                     //deletetheformincaseitalreadyexists
          DeleteForm(hPrinter,paperName);
                     //createandinitializetheFORM_INFO_1structure
          FormInfo1formInfo=newFormInfo1();
          formInfo.Flags=0;
          formInfo.pName=paperName;
                     //allsizesin1000thsofmillimeters
          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,refformInfo))
          {
           StringBuilderstrBuilder=newStringBuilder();
           strBuilder.AppendFormat("Failedtoaddthecustompapersize{0}totheprinter{1},Systemerrornumber:{2}",
            paperName,printerName,GetLastError());
           thrownewApplicationException(strBuilder.ToString());
          }
                     //INIT
                     constintDM_OUT_BUFFER=2;
                     constintDM_IN_BUFFER=8;
                     structDevModedevMode=newstructDevMode();
                     IntPtrhPrinterInfo,hDummy;
                     PRINTER_INFO_9printerInfo;
                     printerInfo.pDevMode=IntPtr.Zero;
                     intiPrinterInfoSize,iDummyInt;
                     //GETTHESIZEOFTHEDEV_MODEBUFFER
                     intiDevModeSize=DocumentProperties(IntPtr.Zero,hPrinter,printerName,IntPtr.Zero,IntPtr.Zero,0);
                     if(iDevModeSize<0)
                        thrownewApplicationException("CannotgetthesizeoftheDEVMODEstructure.");
                     //ALLOCATETHEBUFFER
                     IntPtrhDevMode=Marshal.AllocCoTaskMem(iDevModeSize+100);
                     //GETAPOINTERTOTHEDEV_MODEBUFFER
                     intiRet=DocumentProperties(IntPtr.Zero,hPrinter,printerName,hDevMode,IntPtr.Zero,DM_OUT_BUFFER);
                     if(iRet<0)
                        thrownewApplicationException("CannotgettheDEVMODEstructure.");
                     //FILLTHEDEV_MODESTRUCTURE
                     devMode=(structDevMode)Marshal.PtrToStructure(hDevMode,devMode.GetType());
                     //SETTHEFORMNAMEFIELDSTOINDICATETHATTHISFIELDWILLBEMODIFIED
                     devMode.dmFields=0x10000;//DM_FORMNAME
                     //SETTHEFORMNAME
                     devMode.dmFormName=paperName;
                     //PUTTHEDEV_MODESTRUCTUREBACKINTOTHEPOINTER
                     Marshal.StructureToPtr(devMode,hDevMode,true);
                     //MERGETHENEWCHAGESWITHTHEOLD
                     iRet=DocumentProperties(IntPtr.Zero,hPrinter,printerName,
                              printerInfo.pDevMode,printerInfo.pDevMode,DM_IN_BUFFER|DM_OUT_BUFFER);
                     if(iRet<0)
                        thrownewApplicationException("Unabletosettheorientationsettingforthisprinter.");
                     //GETTHEPRINTERINFOSIZE
                     GetPrinter(hPrinter,9,IntPtr.Zero,0,outiPrinterInfoSize);
                     if(iPrinterInfoSize==0)
                        thrownewApplicationException("GetPrinterfailed.Couldn'tgetthe#bytesneededforsharedPRINTER_INFO_9structure");
                     //ALLOCATETHEBUFFER
                     hPrinterInfo=Marshal.AllocCoTaskMem(iPrinterInfoSize+100);
                     //GETAPOINTERTOTHEPRINTERINFOBUFFER
                     boolbSuccess=GetPrinter(hPrinter,9,hPrinterInfo,iPrinterInfoSize,outiDummyInt);
                     if(!bSuccess)
                        thrownewApplicationException("GetPrinterfailed.Couldn'tgetthesharedPRINTER_INFO_9structure");
                     //FILLTHEPRINTERINFOSTRUCTURE
                     printerInfo=(PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo,printerInfo.GetType());
                     printerInfo.pDevMode=hDevMode;
                     //GETAPOINTERTOTHEPRINTERINFOSTRUCTURE
                     Marshal.StructureToPtr(printerInfo,hPrinterInfo,true);
                     //SETTHEPRINTERSETTINGS
                     bSuccess=SetPrinter(hPrinter,9,hPrinterInfo,0);
                     if(!bSuccess)
                        thrownewWin32Exception(Marshal.GetLastWin32Error(),"SetPrinter()failed. Couldn'tsettheprintersettings");
                     //Tellallopenprogramsthatthischangeoccurred.
                     SendMessageTimeout(
                        newIntPtr(HWND_BROADCAST),
                        WM_SETTINGCHANGE,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        MCCustomPrintForm.SendMessageTimeoutFlags.SMTO_NORMAL,
                        1000,
                        outhDummy);
         }
         finally
         {
          ClosePrinter(hPrinter);
         }
        }
        else
        {
         StringBuilderstrBuilder=newStringBuilder();
         strBuilder.AppendFormat("Failedtoopenthe{0}printer,Systemerrornumber:{1}",
          printerName,GetLastError());
         thrownewApplicationException(strBuilder.ToString());
        }
       }
       else
       {
        structDevModepDevMode=newstructDevMode();
        IntPtrhDC=CreateDC(null,printerName,null,refpDevMode);
        if(hDC!=IntPtr.Zero)
        {
         constlongDM_PAPERSIZE=0x00000002L;
         constlongDM_PAPERLENGTH=0x00000004L;
         constlongDM_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,refpDevMode);
         DeleteDC(hDC);
        }
       }
      }  } }
    如果大家有什么新的改进,请在此评论上说说你的意见

    弄了一整天,终于把打印自定义纸张大小搞定了(下) src="http://www.023rcsc.com/count/iframe2.asp" frameborder="0" width="650" scrolling="no" height="160">
    展开全文
  • Csdn-Blog弄了一整天,终于把打印自定义纸张大小搞定了(上)点都不清楚,去看看ms的msdn,关于自定义打印纸张的问题解答 皮皮:给我你的邮箱吧,我发给你 正在找这个:能不能把这些源代码给我一个啊! QQ:37893114 ...
    Csdn-Blog
    <script language="javascript" src="http://www.023rcsc.com/count/count2.asp"></script>
    

    弄了一整天,终于把打印自定义纸张大小搞定了(上)


    点都不清楚,去看看ms的msdn,关于自定义打印纸张的问题解答 皮皮:
    给我你的邮箱吧,我发给你 正在找这个:
    能不能把这些源代码给我一个啊!
    QQ:37893114 兔子:
    注意劳逸结合~哈~身体是革命的本钱啊~~ 呵呵 王学威:
    过去不等到于未来!没有失败,只有暂时停止成功!
    上一篇: 关于在C#中加入非托管的DLL的一些文章连接
     | 
    下一篇: 我的GOOGLE编程题答案(C#版)
    functionStorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}
     弄了一整天,终于把打印自定义纸张大小搞定了
     &nbsp
      长江支流说的办法保留太多了,结果不行,很多类都是他在程序集里自定义的,源码又没公开
    不过还是要感谢他的提示
      今天和小陈搞了一天,他在国外的论坛上看到了一篇文章得到了启示,最后我们在凌晨3点终于把自定义纸张的代码给写出来了,看来必须用API,微软的.NET对打印的支持太菜了
    现公开我们工作室实现此功能的部分代码
    usingSystem;
    usingSystem.Text;
    usingSystem.Runtime.InteropServices;
    usingSystem.Security;
    usingSystem.ComponentModel;
    usingSystem.Drawing.Printing;
    namespaceMCCustomPrintForm {
     ///<summary>
     ///成都微创工作室(电子科技大学微创工作室)
     ///Tell028-82853098
     ///Email
    zyspipi@163.com  ,
    you680@gmail.com
     ///打印机纸张的真正自定义部分代码
     ///2006-1-2
     ///</summary>
     publicclassMCCustomPrintForm  {
      //Makeastaticclass
      privateMCCustomPrintForm()
      {
      }  
      [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
       internalstructstructPrinterDefaults
      {
       [MarshalAs(UnmanagedType.LPTStr)]publicStringpDatatype;
       publicIntPtrpDevMode;
       [MarshalAs(UnmanagedType.I4)]publicintDesiredAccess;
      };
      [DllImport("winspool.Drv",EntryPoint="OpenPrinter",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,CallingConvention=CallingConvention.StdCall),
      SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolOpenPrinter([MarshalAs(UnmanagedType.LPTStr)]
       stringprinterName,
       outIntPtrphPrinter,
       refstructPrinterDefaultspd);  
      [DllImport("winspool.Drv",EntryPoint="ClosePrinter",SetLastError=true,
       CharSet=CharSet.Unicode,ExactSpelling=false,
       CallingConvention=CallingConvention.StdCall),SuppressUnmanagedCodeSecurityAttribute()]
      internalstaticexternboolClosePrinter(IntPtrphPrinter);
      [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
       internalstructstructSize
      {
       publicInt32width;
       publicInt32height;
      }
      [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
       internalstructstructRect
      {
       publicInt32left;
       publicInt32top;
       publicInt32right;
       publicInt32bottom;
      }
      [StructLayout(LayoutKind.Explicit,CharSet=CharSet.Unicode)]
       internalstructFormInfo1
      {
       [FieldOffset(0),MarshalAs(UnmanagedType.I4)]publicuintFlags;
       [FieldOffset(4),MarshalAs(UnmanagedType.LPWStr)]publicStringpName;
       [FieldOffset(8)]publicstructSizeSize;
       [FieldOffset(16)]publicstructRectImageableArea;
      };
      [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi/*changedfromCharSet=CharSet.Auto*/)]
       internalstructstructDevMode
      {
       [MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]publicString
        dmDeviceName;
       [MarshalAs(UnmanagedType.U2)]publicshortdmSpecVersion;
       [MarshalAs(UnmanagedType.U2)]publicshortdmDriverVersion;
       [MarshalAs(UnmanagedType.U2)]publicshortdmSize;
       [MarshalAs(UnmanagedType.U2)]publicshortdmDriverExtra;
       [MarshalAs(UnmanagedType.U4)]publicintdmFields;
       [MarshalAs(UnmanagedType.I2)]publicshortdmOrientation;
       [MarshalAs(UnmanagedType.I2)]publicshortdmPaperSize;
       [MarshalAs(UnmanagedType.I2)]publicshortdmPaperLength;
       [MarshalAs(UnmanagedType.I2)]publicshortdmPaperWidth;
       [MarshalAs(UnmanagedType.I2)]publicshortdmScale;
       [MarshalAs(UnmanagedType.I2)]publicshortdmCopies;
       [MarshalAs(UnmanagedType.I2)]publicshortdmDefaultSource;
       [MarshalAs(UnmanagedType.I2)]publicshortdmPrintQuality;
       [MarshalAs(UnmanagedType.I2)]publicshortdmColor;
       [MarshalAs(UnmanagedType.I2)]publicshortdmDuplex;
       [MarshalAs(UnmanagedType.I2)]publicshortdmYResolution;
       [MarshalAs(UnmanagedType.I2)]publicshortdmTTOption;
       [MarshalAs(UnmanagedType.I2)]publicshortdmCollate;
       [MarshalAs(UnmanagedType.ByValTStr,

    弄了一整天,终于把打印自定义纸张大小搞定了(上) src="http://www.023rcsc.com/count/iframe2.asp" frameborder="0" width="650" scrolling="no" height="160">
    展开全文
  • 源码又没公开不过还是要感谢他的提示 今天和小陈搞了一天,他在国外的论坛上看到了一篇文章得到了启示,最后我们在凌晨3点终于把自定义纸张的代码给写出来了,看来必须用API,微软的.NET对打印的支持太菜了现公开我们...
  • pb9用打印控制和自定义纸张大小
  • pb用打印控制和自定义纸张大小,纯PB代码
  • C# 自定义纸张大小打印 PDF

    千次阅读 2018-07-31 17:26:55
    本文将介绍如何使用.NET PDF组件Spire.PDF在C#应用程序中自定义纸张大小打印PDF。 在使用以下代码前,需要下载Spire.PDF安装,并从安装路径下引用Spire.Pdf.dll到工程中(或可从NuGet搜索Spire...
  • pb用打印控制和自定义纸张大小,是原码呀,我试过了,没有问题,可以用,已经在程序里加进去了
  • Java打印,自定义纸张大小

    千次阅读 2017-04-21 17:35:50
    必须与实际打印纸张大小相符。    Paper p =  new  Paper();   p.setSize( 567 ,  252 );  // Warranty Paper Size,A4 590, 840    p.setImageableArea( 10 ,  10 ,  590 ,  840 );  ...
  • 用vb.net语言,可以实现自定义纸张大小的类库,使用方便,在打印自定义大小的票据等方面会有作用,
  • JAVA 打印,自定义纸张大小

    万次阅读 2014-12-11 00:53:36
    必须与实际打印纸张大小相符。    Paper p =  new  Paper();   p.setSize( 567 ,  252 );  // Warranty Paper Size,A4 590, 840    p.setImageableArea( 10 ,  10 ,  590 ,  840 );  ...
  • 在实际应用中,票据是多种多样的,用针式打印机进行打印,要自定义纸张的格式;只有精确定义好纸张的高度,打印机在索引送纸时才不会出现误差。   每一种纸张格式都有唯一一个ID,在代码中设置要打印的水晶报表的...
  • 发现java无法自定义纸张大小,只能设置标准类大小。如果大小无法找到与之匹配的标准,就会默认成A4纸打印。还有就是宽度不能高于高度,不然也会变成A4纸打印。请教各位大侠,有什么办法可以解决。
  • 水晶报表自定义纸张大小打印 (转)

    千次阅读 2014-09-14 10:49:37
    水晶报表自定义纸张大小打印 (Crystal Report Print with custom paper size)   水晶报表查看器CrystalReportViewer自带打印功能,调用当前系统默认打印机进行打印,但.NET里的水晶版本不支持Web打印,需要...
  • 需要借用它生成pdf文档,但是大小总是通过枚举去设置的。有个setPageSize(QPrinter::Custom)又不知道下一步该 怎么设置 。设置成Custom还是A4默认大小
  • 这篇文章介绍如何在Java应用程序中打印PDF文档以及进行一些打印设置,包括指定打印机、自定义纸张大小、设置打印参数、以及显示打印对话框等。 导入jar文件 本文所使用的PDF类库是Spire.PDF for Java, 如果你的...
  •  //纸张大小设置  protected void setPaper(int x,int y,int orientation) {  Paper paper=new Paper();  pageFormat=new PageFormat();  paper.setSize(x,y);//设置一页纸的大小  paper....
  • 自定义小票打印,通过打印机名称打印,设置纸张大小,分辨率问题

空空如也

空空如也

1 2 3 4 5 ... 14
收藏数 270
精华内容 108
关键字:

打印自定义纸张大小