using System; using System.Collections.Generic; using System.Drawing.Printing; using System.IO; using System.IO.Ports; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace InjectionPC { public class LabelPrint { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr CreateFile(string IpFileName, int dwDesiredAccess, int dwShareMode, int IpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile); [DllImport("fnthex32.dll", CharSet = CharSet.Auto)] public static extern int GETFONTHEX(string barcodeText, string fontName, string fileName, int orient, int height, int width, int isBold, int isItalic, StringBuilder returnBarcodeCMD); // 打印中文用 const int OPEN_EXISTING = 3; public void PrintLine(string str, string myPort, string messageshow) { try { if (myPort.Substring(0, 3).Equals("USB", StringComparison.CurrentCultureIgnoreCase)) { PrinterSettings ps = new PrinterSettings(); PrinterHelper.SendStringToPrinter(ps.PrinterName, str.Replace("\r\n", "")); if (messageshow == "Y") { MessageBox.Show("打印完毕!"); } } else if (myPort.Substring(0, 3).Equals("LPT", StringComparison.CurrentCultureIgnoreCase)) { IntPtr iHandle = CreateFile(myPort, 0x40000000, 0, 0, OPEN_EXISTING, 0, 0); if (iHandle.ToInt32() == -1) { MessageBox.Show("LPT1 Port Open Failed!"); } FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs, Encoding.Default); sw.WriteLine(str); sw.Close(); fs.Close(); if (messageshow == "Y") { MessageBox.Show("打印完毕!"); } } else if (myPort.Substring(0, 3).Equals("COM", StringComparison.CurrentCultureIgnoreCase)) { //SerialPort com = new SerialPort(myPort, 9600, Parity.Even, 7, StopBits.One); SerialPort com = new SerialPort(myPort, 115200, Parity.None, 8, StopBits.One); com.Open(); com.Write(str); //(str.Replace("\r\n", "")); com.Close(); if (messageshow == "Y") { MessageBox.Show("打印完毕!"); } } else if (myPort.Substring(0, 3).Equals("TCP", StringComparison.CurrentCultureIgnoreCase)) { PrinterHelper.tcpPrint(str); } } catch (Exception) { throw; } } } }