C# 使用C/S模式操作小票机打印

此方式适用于市场上大多数的小票机 佳博、POS58 等,不适用于有些标签打印机 比如斑马打印机等

直接贴代码:

 

C# 使用C/S模式操作小票机打印
 private FileStream fs = null;
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]//调用系统API打印函数
        public static extern IntPtr CreateFile
        (
            string FileName,          // file name
            uint DesiredAccess,       // access mode
            uint ShareMode,           // share mode
            uint SecurityAttributes,  // Security Attributes
            uint CreationDisposition, // how to create
            uint FlagsAndAttributes,  // file attributes
            string hTemplateFile      // handle to template file
        );


        /// <summary>
        /// 打印小票
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string PrintMsg(string PosPort, string msg, bool isOpenMoneyBox)
        {
            try
            {
                IntPtr iHandle = CreateFile(PosPort, 0x40000000, 0, 0, 3, 0, null);
                if (iHandle.ToInt32() == -1)
                {
                    return "票机连接失败.或者端口号错误.请测试打印机是否正常!";
                }
                else
                {
                    try
                    {
                        fs = new FileStream(iHandle, FileAccess.ReadWrite);
                        StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);   //写数据   
                        sw.WriteLine(msg);
                        //开启钱箱
                        if (isOpenMoneyBox)
                        {
                            sw.Write(((char)27).ToString() + "p" + ((char)0).ToString() + ((char)60).ToString() + ((char)255).ToString());
                        }
                        sw.Flush();
                        sw.Close();
                        fs.Close();
                        return "";
                    }
                    catch (Exception ex)
                    {
                        return ex.InnerException == null ? ex.Message : ex.InnerException.Message;
                    }
                }
            }
            catch (Exception exp)
            {
                return "TPL或者COM口连接失败!";
            }
        }
View Code

 

C# 使用C/S模式操作小票机打印

上一篇:项目经验:GIS建模第三天


下一篇:WPF Input Validation Using MVVM