C# 扫码+BarTender打印

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013934107/article/details/82988154

1.效果图:

2.打印条码模板:

3.SOURCE CODE:

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

namespace Print_Color_Box_Barcode
{
    public partial class Form1 : Form
    {
        BarTender.Application btapp;//引用方法1
        BarTender.Format btformat;//引用方法2
        public String[] Config = { "OrderNumber_Len", "OrderNumber_Str_prefix", "SERVER", "DATABASE", "UID", 
                                     "PWD", "StoredProcedure","BarTenderFileName","Pd_ID","Print_Number","Preview","SN_LEN"};
        public String[] BarTender_Str = { "Pd_ID", "SN_1", "SN_2", "Now_Date" };
        public String[] BarTender_Value = { "NULL","NULL","NULL","NULL"};
        public List<TextBox> kk = new List<TextBox>();//填入控件数组
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ReadCfg("config.ini");//读取配置信息
            kk.Add(this.textBox1);
            kk.Add(this.textBox2);
            kk.Add(this.textBox3);
            kk.Add(this.textBox4);
        }


        public Boolean ReadOrderInfo(String OrderNumber)//读取订单信息
        {
            Boolean Flag = false;
            QueryOrderInfo My_OrderInfo = new QueryOrderInfo(Config[2], Config[3], Config[4], Config[5], Config[6],OrderNumber);
            if (My_OrderInfo.Found_OrderNumber() == true)
            {
                textBox2.Text = My_OrderInfo.OrderTotal.ToString();
                Flag = true;
            }
            return Flag;
        }

        public int W_Read_Print_Count(String FileName,int Item)
        {
            if (Item == 1)//读日志
            {
                try
                {
                    FileStream fs = new FileStream(FileName,FileMode.Open,FileAccess.Read);
                    StreamReader sr = new StreamReader(fs, Encoding.Default);
                    String Temp = string.Empty;
                    if ((Temp = sr.ReadLine()) != null)
                    {
                        textBox3.Text = Temp.Trim();
                    }
                    else
                        textBox3.Text = "1";
                    sr.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    textBox3.Text = "1";
                    return 1;
                }
            }
            else if (Item == 2)//写日志
            {
                try
                {
                    FileStream fs = new FileStream(FileName,FileMode.Create,FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine((Convert.ToInt32(textBox3.Text.Trim())+1).ToString());
                    sw.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    return 2;
                }
            }
            return 0;
        }

        public void ReadCfg(String FileName)
        {
            try
            {
                FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.Default);//读取中文
                String Temp = string.Empty;
                while ((Temp = sr.ReadLine()) != null)
                {
                    String[] Array = Temp.Split(new String[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    int n = 0;
                    foreach (String i in Config)
                    {
                        if (i == Array[0].Trim())
                        {
                            Config[n] = Array[1].Trim();
                            break;
                        }
                        n++;
                    }
                }
                sr.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("未读取到配置文件错误信息如下:\n" + e.ToString());
                System.Environment.Exit(1);//退出主程式返回1
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            label6.Text = "";
            if (textBox1.Text.Length == Convert.ToInt32(Config[0]))
            {
                if (ReadOrderInfo(textBox1.Text.Trim()) == true)
                {
                    BarTender_Value[0] = Config[8].Trim();//生成打印条码ID信息
                    BarTender_Value[3] = "生产日期/Date Packed:" + DateTime.Now.ToString("MM-dd-yyyy");//生成打印条码Date_Now信息
                    textBox1.Enabled = true;
                    textBox4.Enabled = true;
                    button1.Enabled = true;
                    textBox4.Focus();//设置文本框为焦点
                }
                else
                {
                    ShowFailInfo(label6, textBox1, "数据库连接或输入P/N错误!!", 0.3f, 0.5f,1);
                }
            }
            else if (textBox1.Text.Length > Convert.ToInt32(Config[0]))
            {
                ShowFailInfo(label6, textBox1, "输入P/N条码长度超出上线!!", 0.3f, 0.5f,1);
            }
            
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (TextBox ss in kk)
            {
                ss.Enabled = false;
                ss.Text = "";
                button1.Enabled = false;
            }
            textBox1.Enabled = true;
            textBox1.Focus();//设置P/N控件焦点
            button1.Enabled = false;
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            W_Read_Print_Count("Flag.dat", 1);
            label6.Text = "";
            if (textBox4.Text.Length == Convert.ToInt32(Config[11]))
            {
                CompleteMachine_SnQuery My_SnQuery = new CompleteMachine_SnQuery("GPUSERVER", "E_CompleteMachine", "sa", "adminsystem",
                    "usp_Found_CompleteMachine_SN",textBox4.Text.Trim());
                if ((My_SnQuery.QueryTestData()) == true)
                {
                    BarTender_Value[1] = textBox4.Text.Trim();//读取条码信息
                    BarTender_Value[2] = textBox4.Text.Trim();//读取条码信息
                    if (Print_BarTender() == true)
                    {
                        W_Read_Print_Count("Flag.dat", 2);
                        ShowFailInfo(label6, textBox4, "条码打印完成!!", 0.3f, 0.5f, 2);
                    }
                    else
                    {
                        ShowFailInfo(label6, textBox4, "连接打印机出错!!", 0.3f, 0.5f,1);
                    }
                }
                else
                {
                    ShowFailInfo(label6, textBox4, "输入CompleteMachine_SN条码完成整机绑码测试,请返回整机测试工序测试!!", 0.1f, 0.5f,1);
                }
            }
            else if (textBox4.Text.Length > Convert.ToInt32(Config[11]))
            {
                ShowFailInfo(label6,textBox4,"输入CompleteMachine_SN条码长度超出上线!!",0.2f,0.5f,1);
            }
        }

        public void ShowFailInfo(Label L1, TextBox T1, String ShowStr, float Le, float Tp,int Items)
        {
            L1.Left = Convert.ToInt32(groupBox3.Width * Le);
            L1.Top = Convert.ToInt32(groupBox3.Height * Tp);
            if (Items == 1)
            {
                L1.ForeColor = Color.Red;
                L1.Text = ShowStr;
                T1.SelectAll();//选中文本框内容
                T1.Focus();//设置文本框为焦点
            }
            else if (Items == 2)
            {
                L1.ForeColor = Color.Green;
                L1.Text = ShowStr;
                T1.Focus();//设置文本框为焦点
                T1.Text = "";
            }
            
        }

        public Boolean Print_BarTender()
        {
            Boolean Flag = false;
            try
            {
                btapp = new BarTender.Application();
                String BarTender_Filepath = System.Environment.CurrentDirectory + @"\" + Config[7].Trim();//获取模板文件路径
                btformat = btapp.Formats.Open(BarTender_Filepath,false,"");//设置模板文件
                btformat.PrintSetup.NumberSerializedLabels = Convert.ToInt32(Config[9].Trim());//设置打印份数
                int n = 0;
                foreach (String str in BarTender_Str)
                {
                    btformat.SetNamedSubStringValue(str, BarTender_Value[n]);
                    n++;
                }

                if (Config[10].Trim().Equals("YES")) btformat.PrintOut(true, true);//第二个参数设置是否跳出打印属性
                else if (Config[10].Trim().Equals("NO")) btformat.PrintOut(true, false);//第二个参数设置是否跳出打印属性
                Flag = true;
            }
            catch (Exception ex)
            {
                ErrLog(ex.ToString());
                Flag = false;
            }
            btapp.Quit(BarTender.BtSaveOptions.btSaveChanges);//退出时同退退出BarTender进程
            return Flag;
        }

        public void ErrLog(String Text)
        {
            try
            {
                FileStream fs = new FileStream("Error.log", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(Text);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

    public class CompleteMachine_SnQuery : Form1//查询整机测试数据
    {
        private String SERVER;
        private String DATABASE;
        private String UID;
        private String PWD;
        private String StoredProcedure;
        private String OrderNumber;

        public CompleteMachine_SnQuery(String SERVER, String DATABASE, String UID, String PWD, String StoredProcedure, String OrderNumber)
        {
            this.SERVER = SERVER;
            this.DATABASE = DATABASE;
            this.UID = UID;
            this.PWD = PWD;
            this.StoredProcedure = StoredProcedure;
            this.OrderNumber = OrderNumber;
        }

        public Boolean QueryTestData()//查询测试结果
        {
            Boolean Flag = false;
            try
            {
                SqlConnection conn = new SqlConnection("server=" + this.SERVER + ";database=" + this.DATABASE + ";uid=" + this.UID + ";pwd=" + this.PWD);
                conn.Open();
                if (conn.State != ConnectionState.Open)
                {
                    ErrLog("Connection Data Base Err!!");
                    Flag = false;
                    return Flag;
                }
                SqlCommand cmd = new SqlCommand(this.StoredProcedure, conn);//设置存储过程启动
                cmd.CommandType = CommandType.StoredProcedure;//启动数据库存储过程
                cmd.Parameters.Add("@CompleteMachine_SN", this.OrderNumber);
                cmd.Parameters.Add("@rest", 1);//设置返回参数
                cmd.Parameters["@rest"].Direction = ParameterDirection.Output;//启动输出返回
                cmd.ExecuteNonQuery();
                if ((int)cmd.Parameters["@rest"].Value == 0)
                {
                    conn.Close();
                    Flag = true;
                }
                else
                {
                    conn.Close();
                    ErrLog("Connection" + this.SERVER + "Data Base Err!!");
                    Flag = false;
                    return Flag;
                }
            }
            catch (Exception ex)
            {
                ErrLog(ex.ToString());
                Flag = false;
            }
            return Flag;
        }

        public void ErrLog(String Text)
        {
            try
            {
                FileStream fs = new FileStream("Error.log", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(Text);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

    public class QueryOrderInfo : Form1//查询订单信息类
    {
        private String SERVER;
        private String DATABASE;
        private String UID;
        private String PWD;
        private String StoredProcedure;
        private String OrderNumber;
        public int OrderTotal;
        public int CompleteTheOrderNumber;

        public QueryOrderInfo(String SERVER, String DATABASE, String UID, String PWD,String StoredProcedure, String OrderNumber)
        {
            this.SERVER = SERVER;
            this.DATABASE = DATABASE;
            this.UID = UID;
            this.PWD = PWD;
            this.StoredProcedure = StoredProcedure;
            this.OrderNumber = OrderNumber;
            this.OrderTotal = 1;
            this.CompleteTheOrderNumber = 1;
        }

        public bool Found_OrderNumber()//查询,并反回数值
        {
            Boolean Flag = false;
            try
            {
                SqlConnection conn = new SqlConnection("server=" + this.SERVER + ";database=" + this.DATABASE + ";uid=" + this.UID + ";pwd=" + this.PWD);
                conn.Open();
                if (conn.State != ConnectionState.Open)
                {
                    ErrLog("Connection Data Base Err!!");
                    Flag = false;
                    return Flag;
                }
                SqlCommand cmd = new SqlCommand(this.StoredProcedure, conn);//设置存储过程启动
                cmd.CommandType = CommandType.StoredProcedure;//启动数据库存储过程
                cmd.Parameters.Add("@OrderNumber", this.OrderNumber);
                cmd.Parameters.Add("@OrderTotal", this.OrderTotal);
                cmd.Parameters["@OrderTotal"].Direction = ParameterDirection.Output;//设置输出参数的方法
                cmd.Parameters.Add("@CompleteTheOrderNumber", this.CompleteTheOrderNumber);
                cmd.Parameters["@CompleteTheOrderNumber"].Direction = ParameterDirection.Output;//设置输出参数的方法
                cmd.Parameters.Add("@rest", 1);//设置返回参数
                cmd.Parameters["@rest"].Direction = ParameterDirection.Output;//启动输出返回
                cmd.ExecuteNonQuery();

                this.OrderTotal = (int)cmd.Parameters["@OrderTotal"].Value;//添加订单总数
                this.CompleteTheOrderNumber = (int)cmd.Parameters["@CompleteTheOrderNumber"].Value;//添加导入订单总数
                if ((int)cmd.Parameters["@rest"].Value == 0)
                {
                    conn.Close();
                    Flag = true;
                }
                else
                {
                    conn.Close();
                    ErrLog("Connection" + this.SERVER + "Data Base Err!!");
                    Flag = false;
                    return Flag;
                }
            }
            catch (Exception ex)
            {
                ErrLog(ex.ToString());
                Flag = false;
            }
            return Flag;
        }

        public void ErrLog(String Text)
        {
            try
            {
                FileStream fs = new FileStream("Error.log", FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(Text);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
 

4.配置文件:

猜你喜欢

转载自blog.csdn.net/u013934107/article/details/82988154