/**/ /// </summary> /// 获取当前指定打印机的状态 /// </summary> /// <param name="PrinterName">打印机名称</param> /// <returns>打印机状态描述</returns> public static string GetPrinterStatus(string PrinterName) { int intValue = GetPrinterStatusInt(PrinterName); string strRet = string.Empty; switch (intValue) { case 0: strRet = "准备就绪(Ready)"; break; case 0x00000200: strRet = "忙(Busy)"; break; case 0x00400000: strRet = "门被打开(Printer Door Open)"; break; case 0x00000002: strRet = "错误(Printer Error)"; break; case 0x0008000: strRet = "正在初始化(Initializing)"; break; case 0x00000100: strRet = "正在输入或输出(I/O Active)"; break; case 0x00000020: strRet = "手工送纸(Manual Feed)"; break; case 0x00040000: strRet = "无墨粉(No Toner)"; break; case 0x00001000: strRet = "不可用(Not Available)"; break; case 0x00000080: strRet = "脱机(Off Line)"; break; case 0x00200000: strRet = "内存溢出(Out of Memory)"; break; case 0x00000800: strRet = "输出口已满(Output Bin Full)"; break; case 0x00080000: strRet = "当前页无法打印(Page Punt)"; break; case 0x00000008: strRet = "塞纸(Paper Jam)"; break; case 0x00000010: strRet = "打印纸用完(Paper Out)"; break; case 0x00000040: strRet = "纸张问题(Page Problem)"; break; case 0x00000001: strRet = "暂停(Paused)"; break; case 0x00000004: strRet = "正在删除(Pending Deletion)"; break; case 0x00000400: strRet = "正在打印(Printing)"; break; case 0x00004000: strRet = "正在处理(Processing)"; break; case 0x00020000: strRet = "墨粉不足(Toner Low)"; break; case 0x00100000: strRet = "需要用户干预(User Intervention)"; break; case 0x20000000: strRet = "等待(Waiting)"; break; case 0x00010000: strRet = "正在准备(Warming Up)"; break; default: strRet = "未知状态(Unknown Status)"; break; } return(strRet); } #endregion 获取当前指定打印机的状态 #region 除已经存在的自定义纸张 /**/ /// <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 { } } }
internal static int GetPrinterStatusInt(string PrinterName) { int intRet = 0; IntPtr hPrinter; structPrinterDefaults defaults = new structPrinterDefaults(); if (OpenPrinter(PrinterName, out hPrinter, ref defaults)) { int cbNeeded = 0; bool bolRet = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out cbNeeded); if (cbNeeded > 0) { IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); bolRet = GetPrinter(hPrinter, 2, pAddr, cbNeeded, out cbNeeded); if (bolRet) { PRINTER_INFO_2 Info2 = new PRINTER_INFO_2(); Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2)); intRet = System.Convert.ToInt32(Info2.Status); } Marshal.FreeHGlobal(pAddr); } ClosePrinter(hPrinter); } return(intRet); }
/// <summary> /// Delete existed form /// </summary> 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 { System.Windows.Forms.MessageBox.Show("Error to delete existed form!"); } } }
/// <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 { "删除自定义纸张时发生错误!".WriteToLog("", log4net.Core.Level.Error); //Pub.WinForm.Msg.Warning("删除自定义纸张时发生错误!"); } } }
/// /// 设置打印纸类型的尺寸,如果没有参数提供的类型则新建一个类型, /// /// 打印机名称 /// 打印纸类型名称 /// 宽度,单位0.1毫米,需要在打印机允许的尺寸之内,否则按照默认打印纸类型打印 /// 高度,单位0.1毫米,需要在打印机允许的尺寸之内,否则按照默认打印纸类型打印 public void SetPrintForm(string printerName, string paperName, float width, float height) { 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 { structFormInfo1 formInfo = new structFormInfo1(); formInfo.Flags = 0; formInfo.pName = paperName; 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; bool rslt = false; if (GetPrintForm(printerName, paperName) != null) { rslt = SetForm(hPrinter, paperName, 1, ref formInfo); } else { this.AddCustomPaperSize(printerName, paperName, width, height); rslt = true; } if (!rslt) { StringBuilder strBuilder = new StringBuilder(); strBuilder.AppendFormat("添加纸张{0}时发生错误!, 系统错误号: {1}", paperName, GetLastError()); //throw new ApplicationException(strBuilder.ToString()); MessageBox.Show(strBuilder.ToString()); } } finally { ClosePrinter(hPrinter); } } } }
private static structPrinterDefaults InitPrinterDefaults() { 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; return(defaults); }
public void DeleteAllPrintForm(string printerName) { structPrinterDefaults defaults = InitPrinterDefaults(); IntPtr hPrinter = IntPtr.Zero; if (OpenPrinter(printerName, out hPrinter, ref defaults)) { try { var printerSettings = PrinterSelector.DefaultPrinterSettings; foreach (PaperSize ps in printerSettings.PaperSizes) { bool ret = DeleteForm(hPrinter, ps.PaperName); Debug.WriteLine("delete ret:" + ret.ToString()); } } finally { ClosePrinter(hPrinter); } } }
// SendBytesToPrinter() // When the function is given a printer name and an unmanaged array // of bytes, the function sends those bytes to the print queue. // Returns true on success, false on failure. public static bool sendBytesToPrinter(string printer_name, IntPtr pBytes, Int32 dwCount) { Int32 dwError = 0, dwWritten = 0; IntPtr hPrinter = new IntPtr(0); DOCINFOA di = new DOCINFOA(); bool bSuccess = false; // Assume failure unless you specifically succeed. di.pDocName = "RAW Document"; di.pDataType = "RAW"; structPrinterDefaults defaults = new structPrinterDefaults(); // Open the printer. if (OpenPrinter(printer_name.Normalize(), out hPrinter, ref defaults)) { // Start a document. if (StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (StartPagePrinter(hPrinter)) { // Write your bytes. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten); EndPagePrinter(hPrinter); } EndDocPrinter(hPrinter); } ClosePrinter(hPrinter); } // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } return(bSuccess); }
/// <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); } } }
private static extern bool OpenPrinter(string printer, out IntPtr handle, ref structPrinterDefaults pDefault);
/**/ /// <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); } } }
internal static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPTStr)] string printerName, out IntPtr phPrinter, ref structPrinterDefaults pd);
public static extern bool OpenPrinter(string printer, out IntPtr handle, ref structPrinterDefaults pDefault);
/// /// 增加打印纸类型 /// /// 打印机名称 /// 打印纸类型名称 /// 宽度,单位0.1毫米,需要在打印机允许的尺寸之内,否则按照默认打印纸类型打印 /// 高度,单位0.1毫米,需要在打印机允许的尺寸之内,否则按照默认打印纸类型打印 public void AddCustomPaperSize(string printerName, string paperName, float width, float height) { 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 { DeleteForm(hPrinter, paperName); structFormInfo1 formInfo = new structFormInfo1(); formInfo.Flags = 0; formInfo.pName = paperName; 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("添加纸张{0}时发生错误!, 系统错误号: {1}", paperName, GetLastError()); throw new ApplicationException(strBuilder.ToString()); } } 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)(width * 2.54 * 10000.0); pDevMode.dmPaperLength = (short)(height * 2.54 * 10000.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 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 int GetPrinterStatusInt(string PrinterName) { int intRet = 0; IntPtr hPrinter; structPrinterDefaults defaults = new structPrinterDefaults(); if (OpenPrinter(PrinterName, out hPrinter, ref defaults)) { int cbNeeded = 0; bool bolRet = GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out cbNeeded); if (cbNeeded > 0) { IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); bolRet = GetPrinter(hPrinter, 2, pAddr, cbNeeded, out cbNeeded); if (bolRet) { PRINTER_INFO_2 Info2 = new PRINTER_INFO_2(); Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2)); intRet = System.Convert.ToInt32(Info2.Status); } Marshal.FreeHGlobal(pAddr); } ClosePrinter(hPrinter); } return intRet; }
public void AddCustomPaperSize(string printerName, string paperName, float widthMm, float heightMm) { 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)(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()); //} 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 structure."); } 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 structure."); } devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType()); devMode.dmFields = 0x10000; // DM_FORMNAME 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("Unable to set the orientation setting for this printer."); } 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"); } hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100); 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"); } 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() failed. Couldn't set the printer settings"); } 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); } } }
/// <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); } } }
/// <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); } } }
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 }
/**/ /// <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; 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 { //如果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, PrintAPI.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); } } } /**/ /// <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 { } } }
private static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, ref structPrinterDefaults pd);