using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace ScannerDemo
{
    /// <summary>

    /// 

    /// </summary>


    public partial class Form1 : Form
    {
        private MessageBoxButtons buttons = MessageBoxButtons.OKCancel;
        private bool m_bconncet = false;
        private bool m_isbeepon = true;
        private int m_handle = 0;
        public int count = 0;
        private int mode = 0;
        private string m_csdata = ("ddd");
        private string m_version = ("ddddddddddddddddddddddddddddddddddddddddddddddddddddd");
        public int iExit = 0;
        public delegate void ScannerDataCallback(string pBuf, long dataLen);
        public delegate void TextBoxDelegate();
        
        public struct DtrIscpRsSymbologies
        {

            // UnmanagedType.ByValArray， [MarshalAs(UnmanagedType.U1)]这个非常重要，就是申明对应类型和长度的

           // [MarshalAs(UnmanagedType.U4)]

            public int index;

           // [MarshalAs(UnmanagedType.Bool)]

            public bool bAction;

           // [MarshalAs(UnmanagedType.LPTStr)]

            public unsafe Char* mstr;   

           // [MarshalAs(UnmanagedType.U1)]
            
            public byte type;

        };
       
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_Connect(int Handle);

        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_Disconnect();
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_GetTriggerMode( ref int mode);
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_SetTriggerMode(Int32 mode);
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_SetFactoryDefault();
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_GetFirmwareInfo(string version, long verLen);
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_SetBeepStatus(bool bBeep);
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_Trigger();
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_UnTrigger();
        [DllImport("DTScannerAPI.dll")]
        public  static  extern unsafe int Scanner_EnumSymbolIdentifierClass(DtrIscpRsSymbologies* pSymbologies, ref int count);
       // [DllImport("DTScannerAPI.dll")]
      //  public static extern int Scanner_GetSymbolIdentifierStatus(int index, ref bool bActive);
        [DllImport("DTScannerAPI.dll")]
        public static extern int Scanner_SetSymbolIdentifierStatus(int index, bool bActive);
        [DllImport("DTScannerAPI.dll")]
        //DTScanner_API int _stdcall Scanner_SetDataReceiverCallback(ScannerDataCallback revFun);
        public static extern int Scanner_SetDataReceiverCallback(ScannerDataCallback revFun);
        private DtrIscpRsSymbologies[] symb = new DtrIscpRsSymbologies[37];		//发送缓冲区大小可根据需要设置；
         
        public Form1()
        {
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
        }
        private void ShowErrMsg(int error)
        {
	        string str="";
	        switch(error)
	        {
	        case 0:
		        break;
	        case 1:
		        str = "Interface is invalid";
		        break;
	        case 2:
		        str = "No device found";
		        break;
	        case 3:
		        str = "Time out";
		        break;
	        case 4:
		        str = "Not connected";
		        break;
	        case 5:
		        str = "Dll internal error";
		        break;
	        case 6:
		        str = "Not support";
		        break;
	        case 10:
		        str = "Invalid input buffer";
		        break;
	        case 11:
		        str = "Input buffer length too small";
		        break;
	        default:
		        str = "UnKnown error";
		        break;
	        }
	        if (str.Length != 0)
	        {
                MessageBox.Show(str, "Warning", buttons, 0, 0);
	        }
        }
        private void button1_Click(object sender, EventArgs e)
        {
          //  int cs;
            Cursor.Current = Cursors.WaitCursor;
            bool bActive=false;
            int result;
            if (m_bconncet)
            {
                m_bconncet = false;

                if ((result=Scanner_Disconnect()) == 0)
                {
                    button1.Text = "Connect";
                    button2.Enabled = false;
                   // button3.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                    button6.Enabled = false;
                    button7.Enabled = false;
                    button8.Enabled = false;
                    button9.Enabled = false;
                    listBox1.Enabled = false;
                    listBox2.Enabled = false;
                    comboBox2.Enabled = false;
                    checkBox1.Enabled = false;
                    textBox1.Enabled = false;
                }
            }
            else
            {
                if (comboBox1.SelectedIndex != 0)
                    return;
                result=Scanner_Connect(1);
                if (result == 0)
                {
                    button1.Text = "Disconnect";
                    button2.Enabled = true;
                  //  button3.Enabled = true;
                    button4.Enabled = true;
                    button5.Enabled = true;
                    button6.Enabled = true;
                    button7.Enabled = true;
                    button8.Enabled = true;
                    button9.Enabled = true;
                    listBox1.Enabled = true;
                    listBox2.Enabled = true;
                    comboBox2.Enabled = true;
                    checkBox1.Enabled = true;
                    textBox1.Enabled = true;
                    Scanner_GetFirmwareInfo(m_version, 256);
                    Scanner_SetBeepStatus(true);
                    button2.Text = "Beep Off";
                    textBox2.Text = m_version;
                    //comboBox1.SelectedIndex = 0;
               
                    unsafe
                    {
                        fixed (DtrIscpRsSymbologies* meptr = symb)
                        {count = 100;
                            Scanner_EnumSymbolIdentifierClass(meptr, ref count);
                           // cs = count;
                           // MessageBox.Show(cs.ToString());
                            for (int i = 0; i < count; i++)
                            {
                                bActive = meptr[i].bAction;
                                string str = new string(meptr[i].mstr);
                               
                                if (bActive)
                                {
                                    listBox2.Items.Add(str);
                                }
                                else
                                {
                                    listBox1.Items.Add(str);
                                }

                            }
                        }
                    }
                   
                   
                    m_bconncet = true;
                    m_csdata = "";
                    textBox1.Text = m_csdata;

                    if (Scanner_GetTriggerMode(ref mode) == 0)
			        {
                        comboBox2.SelectedIndex = mode;
			        }


                    ScannerDataCallback callbackDelegate = new ScannerDataCallback(revFun);
                    if (0 == Scanner_SetDataReceiverCallback(callbackDelegate))
                    {
                        // MessageBox.Show("23");
                    }
                    else
                    {
                        //  MessageBox.Show("24");
                    }
                }
               
            }
            Cursor.Current = Cursors.Default;
            ShowErrMsg(result);
        }
        private void revFun(string pBuf, long dataLen)
        {
            m_csdata = pBuf;
          
            TextBoxHandle(m_csdata);
        }
        private void TextBoxHandle(string sData)
        {
            if (!textBox1.InvokeRequired)  //如果在UI主线程操作ListBox，
            {
               // MessageBox.Show("zzzz");
                textBox1.Text += sData;  //则直接进行控件操作，“与UI主线程相关联”
            }
            else  //如果是在另一线程操作TextBox,则启用委托
            {
                if (iExit == 0)
                {
                   // 
                    textBox1.Invoke(new TextBoxDelegate(TextShow));
                }
            }
        }
        private void TextShow()
        {//MessageBox.Show("aaaa");
            int i;
            Char[] buf = new Char[28] {Convert.ToChar(0x01),Convert.ToChar(0x02),Convert.ToChar(0x03),Convert.ToChar(0x04),Convert.ToChar(0x05),Convert.ToChar(0x06),Convert.ToChar(0x07),Convert.ToChar(0x08),Convert.ToChar(0x09),Convert.ToChar(0x0b),Convert.ToChar(0x0C),Convert.ToChar(0x0e),Convert.ToChar(0x0f),Convert.ToChar(0x10),Convert.ToChar(0x11),Convert.ToChar(0x13),Convert.ToChar(0x14),Convert.ToChar(0x15),Convert.ToChar(0x16),Convert.ToChar(0x17),Convert.ToChar(0x18),Convert.ToChar(0x19),Convert.ToChar(0x1a),Convert.ToChar(0x1b),Convert.ToChar(0x1c),Convert.ToChar(0x1d),Convert.ToChar(0x1e),Convert.ToChar(0x1f)};
           
            while (true)
            {
                i = m_csdata.IndexOfAny(buf);
               // MessageBox.Show(i.ToString());
                if (i == -1)
                    break;
               m_csdata = m_csdata.Remove(i, 1);
            }
            
            m_csdata = m_csdata.Replace("\r\n", "\r");
            m_csdata = m_csdata.Replace("\r", "\r\n");
                //m_csdata.Remove(0x1d);
            //wchar_t a = 0x1d;
            byte a = 0x1d;

            int foundS1 = m_csdata.IndexOf(Convert.ToChar(a));
          //  MessageBox.Show(foundS1.ToString());
            while (-1 != foundS1)
            {
                m_csdata = m_csdata.Remove(foundS1 , 1);
                foundS1 = m_csdata.IndexOf(Convert.ToChar(a));
               // MessageBox.Show(foundS1.ToString());
            }
           //int foundS2 = name->IndexOf( " ", foundS1 + 1 );
       /*    if ( foundS1 != foundS2 && foundS1 >= 0 )
           {
              
             // Console::WriteLine( "After removing the middle name, we are left with '{0}'", name );
           }*/

            textBox1.Text += m_csdata;
           // MessageBox.Show("aa");
            textBox1.Text += "\r\n";
          //  textBox1.ScrollBars = ScrollBars.Vertical;
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.ScrollToCaret();
        }
        private void button2_Click_1(object sender, EventArgs e)
        {
            int result;
            if (m_bconncet)
            {
                if (!m_isbeepon)
                {
                    button2.Text = "Beep Off";
                    m_isbeepon = true;
                    result = Scanner_SetBeepStatus(true);
                }
                else
                {
                    button2.Text = "Beep On";
                    m_isbeepon = false;
                    result = Scanner_SetBeepStatus(false);
                }
                ShowErrMsg(result);
            }
        }

      /*  private void button3_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                Scanner_SetBeepStatus(false);
            }
        }*/

        private void button5_Click(object sender, EventArgs e)
        {
            bool bActive = false;
            int result;
            Cursor.Current = Cursors.WaitCursor;
            if (m_bconncet)
            {
                result = Scanner_SetFactoryDefault();
                if(result != 0)
                {
                    ShowErrMsg(result);
                    return;
                }
                button2.Text = "Beep Off";
                m_isbeepon = true;
                listBox1.Items.Clear();
                listBox2.Items.Clear();
               // m_bconncet = false;
                if (Scanner_Disconnect() == 0)
                {
                    button1.Text = "Connect";
                  /*  button2.Enabled = false;
                    // button3.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                    button6.Enabled = false;
                    button7.Enabled = false;
                    button8.Enabled = false;
                    button9.Enabled = false;
                    listBox1.Enabled = false;
                    listBox2.Enabled = false;
                    comboBox2.Enabled = false;
                    checkBox1.Enabled = false;
                    textBox1.Enabled = false;*/
                }
              /*  if (comboBox1.SelectedIndex != 0)
                    return;*/
                if (Scanner_Connect(1) == 0)
                {
                    button1.Text = "Disconnect";
                   /* button2.Enabled = true;
                    //  button3.Enabled = true;
                    button4.Enabled = true;
                    button5.Enabled = true;
                    button6.Enabled = true;
                    button7.Enabled = true;
                    button8.Enabled = true;
                    button9.Enabled = true;
                    listBox1.Enabled = true;
                    listBox2.Enabled = true;
                    comboBox2.Enabled = true;
                    checkBox1.Enabled = true;
                    textBox1.Enabled = true;*/
                   // Scanner_GetFirmwareInfo(m_version, 256);
                   // Scanner_SetBeepStatus(true);
                   // button2.Text = "Beep Off";
                    //textBox2.Text = m_version;
                    //comboBox1.SelectedIndex = 0;

                    unsafe
                    {
                        fixed (DtrIscpRsSymbologies* meptr = symb)
                        {
                            count = 100;
                            Scanner_EnumSymbolIdentifierClass(meptr, ref count);
                            // cs = count;
                            // MessageBox.Show(cs.ToString());
                            for (int i = 0; i < count; i++)
                            {
                                bActive = meptr[i].bAction;
                                string str = new string(meptr[i].mstr);

                                if (bActive)
                                {
                                    listBox2.Items.Add(str);
                                }
                                else
                                {
                                    listBox1.Items.Add(str);
                                }

                            }
                        }
                    }


                    m_bconncet = true;
                    m_csdata = "";
                    textBox1.Text = m_csdata;

                    if (Scanner_GetTriggerMode(ref mode) == 0)
                    {
                        comboBox2.SelectedIndex = mode;
                    }


                    ScannerDataCallback callbackDelegate = new ScannerDataCallback(revFun);
                    if (0 == Scanner_SetDataReceiverCallback(callbackDelegate))
                    {
                        // MessageBox.Show("23");
                    }
                    else
                    {
                        //  MessageBox.Show("24");
                    }
                }
                if (checkBox1.Checked)
                {
                    // MessageBox.Show("23");
                    Scanner_SetSymbolIdentifierStatus(-1, false);
                    button8.Enabled = false;
                    button9.Enabled = false;
                    listBox1.Enabled = false;
                    listBox2.Enabled = false;
                }

            }
            Cursor.Current = Cursors.Default;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            int result;
            if (m_bconncet)
            {
                result = Scanner_Trigger();
                ShowErrMsg(result);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            int result;
            if (m_bconncet)
            {
                result = Scanner_UnTrigger();
                ShowErrMsg(result);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            int result;
            if (m_bconncet)
            {
                result = Scanner_SetTriggerMode(comboBox2.SelectedIndex);
                ShowErrMsg(result);
            }
        }

        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (checkBox1.Checked)
                {
                    // MessageBox.Show("23");
                    Scanner_SetSymbolIdentifierStatus(-1, false);
                    button8.Enabled = false;
                    button9.Enabled = false;
                    listBox1.Enabled = false;
                    listBox2.Enabled = false;

                }
                else
                {
                    button8.Enabled = true;
                    button9.Enabled = true;
                    listBox1.Enabled = true;
                    listBox2.Enabled = true;
                    for (int i = 0; i < count; i++)
                    {
                        if (symb[i].bAction)
                        {
                            // MessageBox.Show("zhang");
                            Scanner_SetSymbolIdentifierStatus(symb[i].index, true);
                        }
                    }
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            int listcount = listBox1.Items.Count;
            int cs;
            if (m_bconncet)
            {
                if (listcount < 0)
                    return;
                if (checkBox1.Checked)
                    return;
                string str = "";

                if (listBox1.SelectedItem == null)
                {
                    return;
                }
                unsafe
                {
                    fixed (DtrIscpRsSymbologies* meptr = symb)
                    {
                        for (int j = 0; j < count; j++)
                        {
                            string symbstr = new string(meptr[j].mstr);
                            if (0 == listBox1.SelectedItem.ToString().CompareTo(symbstr))
                            {
                                Scanner_SetSymbolIdentifierStatus(meptr[j].index, true);
                                this.listBox2.Items.Insert(0, symbstr);
                                this.listBox1.Items.Remove(symbstr);
                                meptr[j].bAction = true;

                                break;
                            }
                        }
                    }
                }
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            int listcount = listBox2.Items.Count;
            if (m_bconncet)
            {
                if (listcount < 0)
                    return;
                if (checkBox1.Checked)
                    return;
                string str = "";

                if (listBox2.SelectedItem == null)
                {
                    return;
                }
                unsafe
                {
                    fixed (DtrIscpRsSymbologies* meptr = symb)
                    {
                        for (int j = 0; j < count; j++)
                        {
                            string symbstr = new string(meptr[j].mstr);
                            if (0 == listBox2.SelectedItem.ToString().CompareTo(symbstr))
                            {
                                Scanner_SetSymbolIdentifierStatus(meptr[j].index, false);
                                this.listBox1.Items.Insert(0, symbstr);
                                this.listBox2.Items.Remove(symbstr);
                                meptr[j].bAction = false;
                                this.listBox1.Refresh();
                                break;
                            }
                        }
                    }
                }
            }
        }

    }
}