C#发送ZPL控制斑马Zebra打印机程序

最近想把斑马打印机集成到自己的C#程序里,找了好多资料,最后采用通过发送ZPL语言给打印机来完成打印这种方式,该程序可以创建、保存、调用ZPL模板,可以修改打印条码的参数并保存到模板里。下面附有部分程序,需要全套源码可以+V:1357448516。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;


namespace ZebarTest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //底部状态栏结果显示
        private void ShowResult(int Result)   //  状态栏结果显示
        {
            //TextError.Text = Client.ErrorText(Result);
            //if (Result == 0)
            //    TextError.Text = TextError.Text + "(" + Client.ExecutionTime.ToString() + "ms)";
        }


        //使用斑马打印机打印
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                RawPrinterHelper.SendStringToPrinter(comboBox1.Text, this.textBox1.Text);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex.Message);
            }
        }

        //扫描打印机
        private void Form1_Load(object sender, EventArgs e)
        {
            //显示时间
            timer1.Start();
            //选择打印机
            if (string.IsNullOrEmpty(comboBox1.Text))
            {
                groupBox1.Enabled = true;
                groupBox2.Enabled = true;
            }

            string template;
            //加载所有模板
            string[] files = Directory.GetFiles("Template");//("D:\\Visual Studio 2019\\VS Project\\Zebra\\ZebarTest1\\Template");
            foreach (string item in files)
            {
                template = item.ToString();
                string str1 = template.Remove(0, 9);
                //string str1 = template.SubString(8);
                comboBox3.Items.Add(str1);
            }

            获取本地计算机上安装的全部打印机,保存到集合strCollects中
            //PrinterSettings.StringCollection strCollects = PrinterSettings.InstalledPrinters;
            //string strPrinterName = string.Empty;
            遍历集合,将全部打印机载入到下拉列表comboBox1中
            //foreach (String strName in strCollects)
            //{
            //    strPrinterName = strName.ToString();
            //    comboBox1.Items.Add(strPrinterName);
            //}
            //comboBox1.SelectedIndex = 0x00;
            #region 绑定打印机名称
            foreach (string item in PrinterSettings.InstalledPrinters)//获取安装在本计算机上的所有打印机名称
            {
                comboBox1.Items.Add(item);
            }
            if (comboBox1.Items.Contains("ZDesigner GK888t (EPL)"))
            {
                comboBox1.Text = "ZDesigner GK888t (EPL)";
            }

            //备用
            //private void Smt_Zebra_WinForm_ZPL_Load(object sender, EventArgs e)
            //{
            //    PrinterSettings.StringCollection _strCollects = PrinterSettings.InstalledPrinters;

            //    string _strPrinterName = string.Empty;
            //    foreach (String _strName in _strCollects)
            //    {
            //        _strPrinterName = _strName.ToString();
            //        comboBox1.Items.Add(_strPrinterName);
            //    }
            //    comboBox1.SelectedIndex = 0x00;
            //}

            #endregion
            #region 设置默认值
            cbFenBianLv.SelectedIndex = 0;
            txtBiaoQianX.Text = "0";
            txtBiaoQianY.Text = "0";
            txtPrintX.Text = "10";
            txtPrintY.Text = "10";
            cbZhaiTiaoKuanDu.Text = "2";
            cbBiLi.SelectedIndex = 0;
            txtBarHeight.SelectedIndex = 0;
            cbPSD.SelectedIndex = 0;
            cbHSD.SelectedIndex = 3;
            cbFSD.SelectedIndex = 3;
            cbPrintZhuShi.SelectedIndex = 0;
            cbZhuShiHangWeiZhi.SelectedIndex = 1;
            cbZitiName.SelectedIndex = 0;
            cbZitiFangXiang.SelectedIndex = 0;
            txtH.SelectedIndex = 0;
            txtW.SelectedIndex = 0;
            txtPrintNeiRong.Text = "test text";

            //二维码参数
            cbQrOrientation.SelectedIndex = 0;
            cbQrModel.SelectedIndex = 1;
            cbQrMagnification.SelectedIndex = 1;
            cbQrSafe.SelectedIndex = 0;
            cbQrMaskValue.SelectedIndex = 0;
            #endregion
        }

        //激活配方
        public string printPath;
        private void button3_Click(object sender, EventArgs e)
        {
            printPath = comboBox3.Text;
            if (printPath == String.Empty)
            {
                MessageBox.Show("请选择你的模板");
                comboBox3.Focus();
            }
            else
            {
                //MessageBox.Show(printPath);
                //【1】创建文件流
                FileStream fs = new FileStream("Template\\" + printPath, FileMode.Open);
                //【2】创建读取器
                StreamReader sr = new StreamReader(fs);
                //【3】以流的方式读取数据
                this.textBox1.Text = sr.ReadToEnd();
                //【4】关闭读取器
                sr.Close();
                //【5】关闭文件流
                fs.Close();
                //  RawPrinterHelper.SendStringToPrinter(comboBox1.Text, this.textBox1.Text);

                showSelectSet(textBox1.Text);
            }
        }


        private void showSelectSet(string ReadStr)
        {
            if (ReadStr!="")
            {
                cbFenBianLv.Text = Search_string(ReadStr,"JM", "^LH").ToString().Trim();//读取分辨率
                string strBiaoQian= Search_string(ReadStr, "LH", "^FO").ToString().Trim();//读取标签原点坐标
                txtBiaoQianX.Text = StrCutAFront(strBiaoQian,",");//读取坐标原点X坐标
                txtBiaoQianY.Text = StrCutABehind(strBiaoQian, ",");//读取坐标原点Y坐标
                string strDayin = Search_string(ReadStr, "FO", "^BY").ToString().Trim();//读取打印起始位置坐标
                txtPrintX.Text = StrCutAFront(strDayin, ",");//读取打印起始X位置坐标
                txtPrintY.Text = StrCutABehind(strDayin, ",");//打印起始Y位置坐标
                string StrSpeed= Search_string(ReadStr, "PR", "^A").ToString().Trim();//读取速度设置字符串
                cbPSD.Text = StrCutAFront(StrSpeed, ",");//读取打印速度
                string strSP = StrCutABehind(StrSpeed, ",");
                cbHSD.Text = StrCutAFront(strSP, ",");//读取回转速度
                cbFSD.Text = StrCutABehind(strSP, ","); //读取反馈速度
                string strA= StrCutABehind(ReadStr, "^A"); //读取字体设置后面字符串
                cbZitiName.Text = strA.Substring(1,1);//读取字体名称
                cbZitiFangXiang.Text = strA.Substring(2, 1);//读取字体名称
                string strA1 = StrCutABehind(strA, ",");
                txtH.Text = StrCutAFront(strA1, ",");//读取字体高度
                string strA2= StrCutABehind(strA1, ",");
                txtW.Text = StrCutAFront(strA2, "\t");//读取字体宽度
                txtPrintNeiRong.Text = Search_string(ReadStr, "FD", "^FS").ToString().Trim();//读取写打印内容

            }
           
        }


        //参数设置打印
        private void button2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBox1.Text))
            {
                string printNeiRong = "^FD" + txtPrintNeiRong.Text + "^FS";       //打印内容
                textBox3.Text = "Print==>" + txtPrintNeiRong.Text;
                #region 指令语法
                /*                带【】符号表示可以不设置
                 ^XA              表示新标签内容开始  
                 【^JMn 】        改变每毫米打点数 n=A 打印机使用当前最高分辨率,n=B 打印分辨率减半
                 ^LH0,0           设置标签原点座标 x:标签原点的横坐标; y:标签原点的纵坐标 
                 ^FO203,203       设置相对于标签原点的打印起始点座标
                 ^BY3,2.4,50      设置条码格式参数   
                                  w:条码中窄条的宽度,单位 dot,默认值:2dot,值范围:1~10dot; 
                                  r:窄条和宽条的比例,默认值:3,值范围:2~3; 
                                  h:条码高度:默认值 10dot 值范围 100~标签高度

                 //^B3N,Y,,Y,N
                 【^PRp,s,b 】    改变打印速度 
                                  p:打印速度,默认值:A,值范围:A~E(或2~8); 
                                  s:回转速度,默认值:D,值范围:A~E(或2~8)A~E;  
                                  b:反馈速度,默认值:D,值范围:A~E(或2~8)A~E;
                 
                 【^Af,o,h,w】    设置字符字体 
                                  f:字体参数; 
                                  o:字符方向参数,默认值:N,值范围:N(正常)、R(90度)、I(180)、B(270度); 
                                  h:字符高度; 
                                  w:字符宽度;
                 * 
                 * 
                【^BCo,h,f,g,e,m】          设置128-B码打印格式 
                                            o:字符方向参数,默认值:N,值范围:N、R、I、B;     
                                            h:条码高度; 
                                            f:打印解释行,Y为打印,N为不打印; 
                                            g、解释行在条码上方还是下方,Y在条码上方,N在条码下方


                 ^FDABC123^FS     将FD后面的字符打印出来 即打印内容    (^FS表明要打印的内容结束)
                 ^XZ 
                 */
                #endregion
                //comboBox1.Text.Trim() == "";判断是否为空
            }
            else                                //(string.IsNullOrEmpty(comboBox1.Text.Trim()))
            {
                MessageBox.Show("请选择您的打印机");
                comboBox1.Focus();
            }
        }

        //条形码写入
        private void button8_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBox1.Text))
            {
                #region 参数变量
                string fenBianLv = "^JM" + cbFenBianLv.SelectedItem.ToString();      //  分辨率
                string biaoQianZuoBiao = "^LH" + txtBiaoQianX.Text + "," + txtBiaoQianY.Text;    //标签坐标
                string printStartEndZuoBiao = "^FO" + txtPrintX.Text + "," + txtPrintY.Text;      // 打印起始坐标
                string tiaomaCanshu = "^BY" + cbZhaiTiaoKuanDu.Text + "," + cbBiLi.SelectedItem.ToString() + "," + txtBarHeight.Text;     //条码宽度、比例和高度
                string ChangeSuDu = "^PR" + cbPSD.SelectedItem.ToString() + "," + cbHSD.SelectedItem.ToString() + "," + cbFSD.SelectedItem.ToString();     // 打印、回转、反馈速度
                string setZiti = "^A" + cbZitiName.SelectedItem.ToString() + cbZitiFangXiang.SelectedItem.ToString() + "," + txtH.SelectedItem.ToString() + "," + txtW.SelectedItem.ToString();    //字体参数,包括名称、方向、高度和宽度
                string barCodeType = "^BCN" + cbZhaiTiaoKuanDu.Text + "," + txtBarHeight.SelectedItem.ToString() + "," + cbPrintZhuShi.SelectedItem.ToString() + "," + cbZhuShiHangWeiZhi.SelectedItem.ToString();     //条码编码类型,条码宽度 条码高度,是否打印注释,注释行位置
                string printNeiRong = "^FD" + txtPrintNeiRong.Text + "^FS";       //打印内容
                #endregion
                textBox1.Text = "^XA" + "\t" + fenBianLv + "\t" + biaoQianZuoBiao + "\t" + printStartEndZuoBiao + "\t" + tiaomaCanshu + "\t" + ChangeSuDu + "\t" + setZiti + "\t" + barCodeType + "\t" + printNeiRong + "\t" + "^XZ";
            }
            else                                //(string.IsNullOrEmpty(comboBox1.Text.Trim()))
            {
                MessageBox.Show("请选择您的打印机");
                comboBox1.Focus();
            }

        }

        //条形码打印
        private void button4_Click(object sender, EventArgs e)
        {
            // 发送一个打印指令到打印机 cmbInstalledPrinters.Text打印机名称, this.richTextBox2.Text(指令)
            RawPrinterHelper.SendStringToPrinter(comboBox1.Text, this.textBox1.Text);
        }


        //保存为模板
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string newTemplate = textBox2.Text + ".TXT";
                //【1】创建文件流
                FileStream fs = new FileStream("template\\" + newTemplate, FileMode.Create);
                //【2】创建写入器
                StreamWriter sw = new StreamWriter(fs);
                //【3】以流的方式写入数据
                sw.WriteLine(this.textBox1.Text.Trim());
                sw.Close();
                //【5】关闭文件流
                fs.Close();
                //刷新Combox内容
                comboBox3.Items.Add(newTemplate);

            }
            catch (Exception ex)
            {
                MessageBox.Show("There is an IOException" + ex.Message);
            }
            MessageBox.Show("Save Succeed!", "验证提示", MessageBoxButtons.YesNoCancel);
        }

        //删除此模板
        private void button6_Click(object sender, EventArgs e)
        {

            File.Delete("Template\\" + this.comboBox3.Text.Trim());
            //判断是否删除成功
            if (!File.Exists("Template\\" + this.comboBox3.Text.Trim()))
            {
                MessageBox.Show("Delete Success!");
            }
            else { MessageBox.Show("Delete Fail!"); }

            comboBox3.Text = "";
            //刷新Combox内容
            comboBox3.Items.Clear();
            string[] files = Directory.GetFiles("Template");//("D:\\Visual Studio 2019\\VS Project\\Zebra\\ZebarTest1\\Template");
            foreach (string item in files)
            {
                string template = item.ToString();
                string str1 = template.Remove(0, 9);
                //string str1 = template.SubString(8);
                comboBox3.Items.Add(str1);
            }

        }


        //显示时间组件
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = System.DateTime.Now;
            label35.Text = dt.ToString();

        }


        //二维码写入
        private void button9_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBox1.Text))
            {
                string fenBianLv = "^JM" + cbFenBianLv.SelectedItem.ToString();      //  分辨率
                string biaoQianZuoBiao = "^LH" + txtBiaoQianX.Text + "," + txtBiaoQianY.Text;    //标签坐标
                string printStartEndZuoBiao = "^FO" + txtPrintX.Text + "," + txtPrintY.Text;      // 打印起始坐标
                string printQr = "^BQ" + cbQrOrientation.SelectedItem.ToString() + "," + cbQrModel.SelectedItem.ToString() + "," + cbQrMagnification.SelectedItem.ToString();       //二维码参数
                string ChangeSuDu = "^PR" + cbPSD.SelectedItem.ToString() + "," + cbHSD.SelectedItem.ToString() + "," + cbFSD.SelectedItem.ToString();     // 打印、回转、反馈速度
                string setZiti = "^A" + cbZitiName.SelectedItem.ToString() + cbZitiFangXiang.SelectedItem.ToString() + "," + txtH.SelectedItem.ToString() + "," + txtW.SelectedItem.ToString();    //字体参数,包括名称、方向、高度和宽度
                                      //       纠错级别                        输入模式(M, 手动输入   A自动模式)                   字符模式(N 数字数据    A 字母数字数据)              数据字符串
                string printNeiRong = "^FD" + cbQrSafe.SelectedItem.ToString() + cbQrMaskValue.SelectedItem.ToString() + ","+ txtPrintNeiRong.Text + "^FS";       //打印内容#endregion
                textBox1.Text = "^XA" + "\t" + fenBianLv + "\t" + biaoQianZuoBiao + "\t" + printStartEndZuoBiao + "\t" + printQr + "\t" + ChangeSuDu + "\t" + setZiti + "\t" + printNeiRong + "\t" + " ^ XZ";
                
            }
            else                                //(string.IsNullOrEmpty(comboBox1.Text.Trim()))
            {
                MessageBox.Show("请选择您的打印机");
                comboBox1.Focus();
            }

        }
        //打印二维码
        private void button7_Click(object sender, EventArgs e)
        {
            RawPrinterHelper.SendStringToPrinter(comboBox1.Text, this.textBox1.Text);
        }

        打印字符串
        //private void button10_Click(object sender, EventArgs e)
        //{
        //    if (!string.IsNullOrEmpty(textBox3.Text))
        //    {

        //        string fenBianLv = "^JM" + cbFenBianLv.SelectedItem.ToString();      //  分辨率
        //        string biaoQianZuoBiao = "^LH" + txtBiaoQianX.Text + "," + txtBiaoQianY.Text;    //标签坐标
        //        string printStartEndZuoBiao = "^FO" + txtPrintX.Text + "," + txtPrintY.Text;      // 打印起始坐标
        //        string setZiti = "^A" + cbZitiName.SelectedItem.ToString() + cbZitiFangXiang.SelectedItem.ToString() + "," + txtH.SelectedItem.ToString() + "," + txtW.SelectedItem.ToString();    //字体参数,包括名称、方向、高度和宽度
        //        string printNeiRong = "^FD" + txtPrintNeiRong.Text + "^FS";       //打印内容
        //        textBox1.Text = "^XA" + "\t" + fenBianLv + "\t" + biaoQianZuoBiao + "\t" + printStartEndZuoBiao + "\t" + setZiti + "\t" + printNeiRong + "\t" + " ^ XZ";
        //    }
        //    else
        //    {
        //        MessageBox.Show("请输入你的字符串! ");
        //    }
        //}


        /// <summary>
        /// 获取两个字符串之间的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <returns></returns>
        private string StrCutAB(string str, string A, string B)
        {
            string Ru = "";
            int IndexofA = str.IndexOf(A);
            int IndexofB = str.IndexOf(B);
            Ru = str.Substring(IndexofA + 1, IndexofB - IndexofA - 1);
            return Ru;
        }

        /// <summary>
        /// 获取字符A后面的字符串
        /// </summary>
        /// <returns></returns>
        private string StrCutABehind(string str, string A)
        {
            string Ru = "";
            int IndexofA = str.IndexOf(A);
            Ru = str.Substring(IndexofA + 1);
            return Ru;

        }

        /// <summary>
        /// 获取字符A前面的字符串
        /// </summary>
        /// <returns></returns>
        private string StrCutAFront(string str, string A)
        {
            string Ru = "";
            int IndexofA = str.IndexOf(A);
            Ru = str.Substring(0, IndexofA);
            return Ru;

        }

        //------//搜索字符串(参数1:目标字符串,参数2:之前字符串,参数3:之后字符串)----(获取两个字符串中间的字符串)
        public static string Search_string(string s, string s1, string s2)  //获取搜索到的数目
        {
            int n1, n2;
            n1 = s.IndexOf(s1, 0) + s1.Length;   //开始位置
            n2 = s.IndexOf(s2, n1);               //结束位置
            return s.Substring(n1, n2 - n1);   //取搜索的条数,用结束的位置-开始的位置,并返回
        }

    
        //------
    }
}

猜你喜欢

转载自blog.csdn.net/u014780302/article/details/115328415
今日推荐