C#后台調用LPT1端口實現小票機打印方法。


public class POSPrinter
    {
        const int OPEN_EXISTING = 3;

        string prnPort = "LPT1";
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr CreateFile(string lpFileName,
        int dwDesiredAccess,
        int dwShareMode,
        int lpSecurityAttributes,
        int dwCreationDisposition,
        int dwFlagsAndAttributes,
        int hTemplateFile);
        public POSPrinter()
        {
        
        }
        public POSPrinter(string prnPort)
        {
            this.prnPort = prnPort;//打印機端口
        }
        public string PrintLine(string str)
        {
            IntPtr iHandle = CreateFile(prnPort, 0x50000000, 0, 0, OPEN_EXISTING, 0, 0);
            if (iHandle.ToInt32() == -1)
            {
                Console.WriteLine(iHandle.ToString());
                return "沒有連接打印機或者打印機端口不是LPT1";
            }
            else
            {
                Console.WriteLine(iHandle.ToString());
                FileStream fs = new FileStream(iHandle, FileAccess.ReadWrite);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                sw.WriteLine("           小票單");
                sw.WriteLine();
                sw.WriteLine(str);
                sw.WriteLine("打印內容");
                sw.WriteLine("---------------------------");

                sw.Close();
                fs.Close();
                return "打印成功!";
            }
        }
    }

  直接調用PrintLine();方法進行打印具體需要的參數和打印格式大家自行調整。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM