
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;
using System.IO;
using System.Threading;


namespace HansAdvInterfaceCSharpTest
{
    public partial class MainForm : Form
    {
        //*********************全局数据定义****************************
        bool m_bInitOk = false;
        double m_dbViewRate = 1.0;
        double m_dbViewX = 0;
        double m_dbViewY = 0;
        bool bDrawing = false;
        bool m_bWaitTouch = false;
        bool m_bWaitEnd = true;
        int m_nWaitTimeForTouch = 0;
        double m_dbBaseX = 0;
        double m_dbBaseY = 0;
        double m_dbParaX = 0;
        double m_dbParaY = 0;
        string m_strTextTxt = "";
        string m_strModelName = "";
        string m_strHansFileName = "default.bs";
        string m_strHansFileNameHS = "default.hs";

        public bool ClickOkBtn = false;
        public bool m_bTouchReport;
        UInt16 m_dwInPort;
        int m_dwOutPort;
        uint m_TouchNum;

        uint g_uCard = 0;
       
        int m_nMarkModel = 0;
        int m_nFlyType = 0;
        double m_dbSpeed = 0.0;

        bool m_bEnableAxis0 = true;
        bool m_bEnableAxis1 = true;
        bool m_bEnableAxis2 = true;
        bool m_bEnableAxis3 = true;
        double m_dbMoveValue0 = 1;
        double m_dbMoveValue1 = 1;
        double m_dbMoveValue2 = 1;
        double m_dbMoveValue3 = 1;

        CSharpInterface.MsgFlyMarkCall msgflyMarkCall = null;

        // by 2024/07/01 运动模式 0:绝对; 1:相对;2:机械原点
        int m_nMoveModel = 1;
        // 运动类型 0:负载; 1:空程
        int m_nMoveType = 0;
        // 是否回软件原点
        bool m_bSoftHome = false;

        // by 2024/07/04 操作预览视图
        bool m_bMove; // 是否已按下鼠标中键/允许预览图拖拽
        bool m_bBoxSelect; // 是否已按下鼠标左键/允许框选
        Point m_ptMoveStart; // 视图移动时的起点，用于计算
        Point m_ptBoxSelectStart; // 鼠标左键框选的起点，用于计算
        Rectangle m_rectBoxSelect; // 框选框

        public void Thread_MotorMove(object para)
        {
            MainForm pDlg = para as MainForm;
            if (pDlg == null)
                return;

            double[] dbValue = new double[8];
            dbValue[0] = pDlg.m_dbMoveValue0;
            dbValue[1] = pDlg.m_dbMoveValue1;
            dbValue[2] = pDlg.m_dbMoveValue2;
            dbValue[3] = pDlg.m_dbMoveValue3;

            int nAxisEx = (pDlg.m_bEnableAxis0 ? 1 : 0) |
                          (pDlg.m_bEnableAxis1 ? 1 << 1 : 0) |
                          (pDlg.m_bEnableAxis2 ? 1 << 2 : 0) |
                          (pDlg.m_bEnableAxis3 ? 1 << 3 : 0);

            int nRtn = CSharpInterface.HS_MoveMotorVEx(pDlg.g_uCard, nAxisEx, dbValue, pDlg.m_nMoveModel, pDlg.m_nMoveType);
        }

        public MainForm()
        {
            InitializeComponent();
            m_bTouchReport = false;
            m_dwInPort = 0;
            m_dwOutPort = 0;
            m_TouchNum = 0;

            this.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.Preview_MouseWheel);
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            GetDllVersion();
            UpdateView();

            string str= "";
            for (int i = 0; i < 16; i++)
            {
                str = i.ToString();
                comboBox_IO.Items.Add(str);
            }
        }
        public void GetDllVersion()
        {
//             ushort nMainVer = 0, nDllVer = 0;
//             if (CSharpInterface.HS_GetDllVersion(ref nMainVer, ref nDllVer) == 0)
//             {
//                 //将二进制数值解析成主版本号
//                 string str1 = ((((1 << 4) - 1) << 12 & nMainVer) >> 12).ToString() +
//                     "." + (((((1 << 5) - 1) << 7) & nMainVer) >> 7).ToString() +
//                     "." + (((1 << 7) - 1) & nMainVer).ToString();
//                 //将二进制数值解析成子版本号
//                 string str2 = ((((1 << 4) - 1) << 12 & nDllVer) >> 12).ToString()
//                     + "." + (((((1 << 5) - 1) << 7) & nDllVer) >> 7).ToString() +
//                     "." + (((1 << 7) - 1) & nDllVer).ToString();
//                 tsslabVersion.Text = str1 + "-" + str2;
//             }
//             else
//             {
//                 ShowLastError();
//                 MessageBox.Show("调用失败");
//             }
        }

        // 脚踏/开始打标信号的回调函数
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case 2119:
                    // 脚踏信号有效消息处理
                    //LaserMark(); // 调用打标流程
                    //MessageBox.Show("脚踏信号已触发", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    m_TouchNum++;
                    tbTouchNum.Text = m_TouchNum.ToString();
                    break;
                default:
                    base.DefWndProc(ref m);//一定要调用基类函数，以便系统处理其它消息。
                    break;
            }
        }

        //初始化打标系统
        private void Initial_System_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            // string strCurPath = System.Environment.CurrentDirectory;
            string strCurPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
            int nRet = CSharpInterface.HS_InitialMachine(strCurPath);
            if (nRet == 0 || nRet == 30)
            {
                tbNote.Text = "打标系统初始化成功！";
                tsslabCardStatus.Text = "状态：初始化成功！";

                CSharpInterface.g_strPathName = strCurPath;
                m_bInitOk = true;

                double px = 0, py = 0;
                CSharpInterface.HS_GetMarkRange(g_uCard,ref px, ref py);
                tsslabMarkRange.Text = "打标范围:" + px.ToString() + "*" + py.ToString() + "mm";

                myImageTab1.TabPages.Add("default");
                SwitchDoc("default");
                Preview();

                //add 2022/05/05
                uint uCard= 0;
                CSharpInterface.HS_GetCardNumber(ref uCard);
                comboBox_Card.Items.Clear();
                for (int i = 0; i < uCard; i++)
                {
                    string str ="Card:" + (i+1).ToString();
                    comboBox_Card.Items.Add(str);
                }
                if (uCard > 0)
                {
                    comboBox_Card.SelectedIndex = 0;
                    g_uCard = 0;
                }

            }
            else
            {
                ShowLastError();
                tsslabCardStatus.Text = "状态：初始化失败！";
            }
            UpdateView();
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        //显示错误信息
        string ShowLastError()
        {
            int nErr = 0;
            StringBuilder szBuff = new StringBuilder(200);
            CSharpInterface.HS_GetLastError(g_uCard, ref nErr, szBuff, 200);
            tbNote.Text = szBuff.ToString();
            return szBuff.ToString();
        }

        //释放打标系统
        private void btnRelease_Click(object sender, EventArgs e)
        {
            int nRet = CSharpInterface.HS_CloseMachine();
            if (0 == nRet)
            {
                tbNote.Text = "释放成功！";
                tsslabCardStatus.Text = "状态：未初始化！";

                m_bInitOk = false;

                tsslabMarkRange.Text = "打标范围：";
                Refresh();
            }
            else
            {
                ShowLastError();
                tsslabCardStatus.Text = "状态：初始化成功！";
            }
            UpdateView();

        }

        //
        public void UpdateView()
        {
            btnModule.Enabled = btnRelease.Enabled = btnModulesClose.Enabled = m_bInitOk;
            groupBox2.Enabled = groupBox3.Enabled = groupBox4.Enabled = groupBox6.Enabled = m_bInitOk;
            myImageTab1.Enabled = m_bInitOk;
            groupBox7.Enabled = m_bInitOk;
            groupBox8.Enabled = m_bInitOk;
            comboBox_Card.Enabled = m_bInitOk;
            btn_MarkAll.Enabled = m_bInitOk;
            btnChangeBitmapByName.Enabled = m_bInitOk;
            tbBmpObjName.Enabled = m_bInitOk;

            checkBox_Axis0.Checked = m_bEnableAxis0;
            checkBox_Axis1.Checked = m_bEnableAxis1;
            checkBox_Axis2.Checked = m_bEnableAxis2;
            checkBox_Axis3.Checked = m_bEnableAxis3;
            textBox_movement0.Text = m_dbMoveValue0.ToString();
            textBox_movement1.Text = m_dbMoveValue1.ToString();
            textBox_movement2.Text = m_dbMoveValue2.ToString();
            textBox_movement3.Text = m_dbMoveValue3.ToString();
            m_btnAMove.Checked = m_nMoveModel == 0;
            m_btnRMove.Checked = m_nMoveModel == 1;
            m_btnMoveLoad.Checked = m_nMoveType == 0;
            m_btnMoveIdle.Checked = m_nMoveType == 1;

            if (myImageTab1 != null)
                myImageTab1.Enabled = m_bInitOk;

            radioBtn_Normal.Checked = true;
            radioBtn_Cons_Speed.Checked = true;
            textBox_Length.Text = Convert.ToString(1000);

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CSharpInterface.HS_CloseMachine();
        }

        //开始打标
        private void btnEarMark_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            int nRet = CSharpInterface.HS_Mark(g_uCard
                , 0                  // 0-激光   1-红光   2-红光边框预览
                , m_bWaitTouch        // 是否等待信号才触发出光
                , m_bWaitEnd          // 是否等待打标结束，接口才返回
                , m_nWaitTimeForTouch  // 等待信号时长
                , true);             // 是否打标所有的对象（否则为选中的对象）

            ShowLastError();
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        //显示打标状态
        private void btnStatus_Click(object sender, EventArgs e)
        {
            int nFlag = 0;
            int nRet = CSharpInterface.HS_IsMarkEnd(g_uCard,ref nFlag);
            if (nRet == 0)
            {
                if (nFlag == 0)
                    tbNote.Text = "打标中......";
                else
                {
                    if (nFlag == 3)
                    {
                        ShowLastError();
                    }
                    int nTime = 0;
                    CSharpInterface.HS_GetMarkTime(g_uCard,ref nTime);
                    tbNote.Text = "打标完成！耗时：" + nTime.ToString() + " ms";
                }
            }
            else
            {
                ShowLastError();
            }
        }

        //停止打标 
        private void btnMarkStop_Click(object sender, EventArgs e)
        {
            int nRet = CSharpInterface.HS_MarkStop(g_uCard);
            if (nRet == 0)
            {
            }
            else
            {
                ShowLastError();
            }

        }

        //显示预览
        void Preview()
        {
            if (bDrawing)
                return;
            bDrawing = true;
            if (pictureBox1.Handle != null)
            {
                //CSharpInterface.HS_PreviewGraphEx(g_uCard, (IntPtr)0, 0, "", 200, 200);
                int nRet = CSharpInterface.HS_PreviewGraph(g_uCard, pictureBox1.Handle, m_dbViewX, m_dbViewY, m_dbViewRate);
                if (nRet != 0)
                    ShowLastError();
            }
            bDrawing = false;
        }

        //获取当前操作对象的属性，并显示在状态栏中
        public void SelectSize()
        {
            double l = 0, t = 0, r = 0, b = 0;
            int nRet = CSharpInterface.HS_GetObjProperty(g_uCard,ref l, ref t, ref r, ref b);
            if (nRet == 0)
            {
                tsslabObjSize.Text = "对象属性:宽[" + (l - r).ToString("f2") + "mm,高:" + (t - b).ToString("f2") +
                    "mm,中心(" + ((r - l) * 0.5).ToString("f2") + ((t - b) * 0.5).ToString() + ")]";
            }
            else
            {
                ShowLastError();
            }
        }

        //移动
        private void btnMove_Click(object sender, EventArgs e)
        {
            try
            {
                m_dbParaX = Convert.ToDouble(tbParaX.Text);
                m_dbParaY = Convert.ToDouble(tbParaY.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("输入的数据不合法！\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int nRet = CSharpInterface.HS_Move(g_uCard,m_dbParaX, m_dbParaY);
            if (nRet == 0)
            {
                Preview();
            }
            else
            {
                ShowLastError();
            }
            SelectSize();
        }

        //旋转
        private void btnRotate_Click(object sender, EventArgs e)
        {
            try
            {
                m_dbParaX = Convert.ToDouble(tbParaX.Text);
                m_dbBaseX = Convert.ToDouble(tbBaseX.Text);
                m_dbBaseY = Convert.ToDouble(tbBaseY.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("输入的数据不合法！\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int nRet = CSharpInterface.HS_Rotate(g_uCard,m_dbBaseX, m_dbBaseY, m_dbParaX);
            if (nRet == 0)
            {
                Preview();
            }
            else
            {
                ShowLastError();
            }
            SelectSize();
        }

        //文本替换(ANSI)
        private void btnChangeTextByID_Click(object sender, EventArgs e)
        {
            m_strModelName = this.tbTextID.Text;
            m_strTextTxt = this.tbTextTXT.Text;
            int nRet = CSharpInterface.HS_ChangeTextByName(g_uCard,m_strModelName, m_strTextTxt);
            if (0 == nRet)
            {
                Preview();
            }
            else
            {
                ShowLastError();
            }
        }

        //文本获取(ANSI)
        private void btnGetTextByID_Click(object sender, EventArgs e)
        {
            m_strModelName = this.tbTextID.Text;
            int nSize = 200;
            StringBuilder szText = new StringBuilder(200);
            int nRet = CSharpInterface.HS_GetTextByName(g_uCard,m_strModelName, szText, ref nSize);
            if (0 == nRet)
            {
            }
            else
            {
                ShowLastError();
                return;
            }

            this.tbTextTXT.Text = m_strTextTxt = szText.ToString();
        }

        //文本替换
        private void btnChangeTextByIDW_Click(object sender, EventArgs e)
        {
            string szText2 = tbTextTXT.Text;
            Byte[] szText = Encoding.Unicode.GetBytes(szText2);
            int nRet = CSharpInterface.HS_ChangeTextByNameW(g_uCard,m_strModelName, szText);
            if (0 == nRet)
            {
            }
            else
            {
                ShowLastError();
                return;
            }
            Preview();
        }

        //文本获取
        private void btnGetTextByIDW_Click(object sender, EventArgs e)
        {
            m_strModelName = this.tbTextID.Text;
            int nSize = 200;
            byte[] szText = new byte[200];
            int nRet = CSharpInterface.HS_GetTextByNameW(g_uCard,m_strModelName, szText, ref nSize);
            if (0 == nRet)
            {
            }
            else
            {
                ShowLastError();
                return;
            }
            this.tbTextTXT.Text = m_strTextTxt = Encoding.Unicode.GetString(szText);
        }

        // 打开模板文件
        private void btnModule_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
#if _DEBUG_HBM || NDEBUG_HBM
            openFileDialog1.Filter = "BS File(*.bs)|*.bs";
#else
            openFileDialog1.Filter = "HS File(*.hs)|*.hs";
#endif
            openFileDialog1.Title = "Open file";
            if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
            int nRet = CSharpInterface.HS_LoadMarkFile(g_uCard,openFileDialog1.FileName);
            if (0 == nRet)
            {
#if _DEBUG_HBM || NDEBUG_HBM
                m_strHansFileName = openFileDialog1.SafeFileName;
                myImageTab1.TabPages.Add(m_strHansFileName);
                myImageTab1.SelectTab(myImageTab1.TabPages.Count - 1);
                SwitchDoc(m_strHansFileName);
#else
                m_strHansFileNameHS = openFileDialog1.SafeFileName;
                myImageTab1.TabPages.Add(m_strHansFileNameHS);
                myImageTab1.SelectTab(myImageTab1.TabPages.Count - 1);
                SwitchDoc(m_strHansFileNameHS);
#endif
                Preview();
            }
            else
            {
                ShowLastError();
            }
        }

        //关闭模板文件
        private void btnModulesClose_Click(object sender, EventArgs e)
        {
           
            bool bSave = false;
            if (DialogResult.Yes == MessageBox.Show("是否保存修改?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                bSave = true;
            }
            int nRet = CSharpInterface.HS_CloseMarkFile(g_uCard,myImageTab1.SelectedTab.Text, bSave);
            if (nRet == 0)
            {
                myImageTab1.TabPages.RemoveAt(myImageTab1.SelectedIndex);
                myImageTab1.TabIndex = 0;
                SelectSize();
                SwitchDoc("default");
                Preview();
            }
            else
            {
                ShowLastError();
            }
        }

        //读取IO
        private void btnReadInPort_Click(object sender, EventArgs e)
        {
            int nRet = CSharpInterface.HS_ReadPort(g_uCard,ref m_dwInPort);
            if (nRet == 0)
            {
                tbNote.Text = "读取输入端口成功!";
                tbInPort.Text = "0x"+Convert.ToString(m_dwInPort,16);
            }
            else
            {
                tbNote.Text = "读取输入端口失败!";
                MessageBox.Show("操作失败!\n返回值:" + m_dwInPort.ToString() + "\n错误:"
                    + CSharpInterface.GetError().ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //输出口写出
        private void btnWriteOutPort_Click(object sender, EventArgs e)
        {
            bool bState = checkBox_IO.Checked;
            try
            {
                m_dwOutPort = Convert.ToInt32(comboBox_IO.Text);
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("请输入一个正整数！\n" + ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                m_dwOutPort = 0;
               
                return;
            }
            if (m_dwOutPort < 0)
            {
                MessageBox.Show("请输入一个正整数！\n", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                m_dwOutPort = 0;
              
                return;
            }
            bool nRet = CSharpInterface.HS_WriteOutPortBit(g_uCard,m_dwOutPort, bState);
            if (nRet == true)
            {
                tbNote.Text = "写输出端口成功";
            }
            else
            {
                tbNote.Text = "写输出端口失败!";
                MessageBox.Show("操作失败!\n返回值:" + nRet.ToString() + "\n错误:"
                    + CSharpInterface.GetError().ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //脚踏查询
        private void btnQueryTouch_Click(object sender, EventArgs e)
        {
            int nFlag = 0;
            int nRet = CSharpInterface.HS_IsTouch(g_uCard,ref nFlag);
            if (nRet != 0)
            {
                tbNote.Text = "脚踏查询失败";
                MessageBox.Show("操作失败!\n返回值:" + nRet.ToString() + "\n错误:"
                   + CSharpInterface.GetError().ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (nFlag != 0)
                {
                    tbNote.Text = "脚踏触发了!";
                    tB_Touch.Text = nFlag.ToString();
                }
                else
                {
                    tbNote.Text = "脚踏没有触发!";
                }
            }
        }
        //IO控制
        private void cbTouchRePort_CheckedChanged(object sender, EventArgs e)
        {
            m_bTouchReport = cbTouchRePort.Checked;
            int nRet = CSharpInterface.HS_CheckTouch(g_uCard,this.Handle, m_bTouchReport);
            if (nRet != 0)
            {
                ShowLastError();
            }
            else
            {
                this.tbNote.Text = "脚踏检测成功!";
            }
        }

        //读取输出口IO
        private void btnReadPort_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            ushort nReadPort = 0;
            int nRet = CSharpInterface.HS_ReadOutPort(g_uCard,ref nReadPort);
            if (nRet == 0)
            {
                tbNote.Text = "读取输出口IO成功!";
                tB_ReadPort.Text = "0x"+Convert.ToString(nReadPort,16);
            }
            else
            {
                ShowLastError();
            }
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        //获取狗ID信息
        private void btGetDogInfo_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            byte[] id = new byte[33];
            byte[] compid = new byte[5];
            byte[] devid = new byte[9];
            bool bRet = CSharpInterface.HS_GetTimeDogInfoID(id, compid, devid);
            if (bRet)
            {
                tB_SN.Text = Encoding.UTF8.GetString(id);
                tB_Client.Text = Encoding.UTF8.GetString(compid);
                tB_DeviceID.Text = Encoding.UTF8.GetString(devid);
            }
            else 
            {
                ShowLastError();
            }

            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        //add 2022/3/8
        private void Preview_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            double OPRATE =1.1;
            int i = 0;
            Rectangle rect=myImageTab1.RectangleToScreen(this.ClientRectangle);
            if (rect.Contains(MousePosition))
            {
                int n = Convert.ToInt32(System.Math.Abs(e.Delta / 120 * 1.0));
                if (e.Delta > 0)
                {
                   
                    for (; i < n; ++i)
                    {
                        m_dbViewRate *= OPRATE;
                    }
                }
                else 
                {
                    for(; i<n; ++i )
			        {
				        m_dbViewRate /= OPRATE; 
		            }
                }
                Preview();
            }
        }
        void SwitchDoc(string strFile)
        {
            int nRet = CSharpInterface.HS_SetCurDoc(g_uCard,strFile);
            ShowLastError();
        }
        private void myImageTab1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SwitchDoc(myImageTab1.SelectedTab.Text);
            Preview();
        }

        //add 2022/04/29
        private void btn_MarkAll_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            int nCount = 0;
            nCount = comboBox_Card.Items.Count;

            for (uint i = 0; i < nCount; i++)
            {
                int nRet = CSharpInterface.HS_Mark(g_uCard
                    , 0
                    , m_bWaitTouch        // 是否等待信号才触发出光
                    , m_bWaitEnd          // 是否等待打标结束，接口才返回
                    , m_nWaitTimeForTouch  // 等待信号时长
                    , true);             // 是否打标所有的对象（否则为选中的对象）
            }

            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        private void comboBox_Card_SelectedIndexChanged(object sender, EventArgs e)
        {
            int nIndex = comboBox_Card.SelectedIndex;
            g_uCard =(uint)nIndex;
           
        }

        public void CustomMsgCall(uint nCard, uint dwCode, Int64 value)
        {
            try
            {
                if (dwCode == 35002)     //接收控制卡周期结束命令
                {
                    //接收的数据
                    IntPtr p1 = (IntPtr)value;
                    USERCMD_PARA r2 = (USERCMD_PARA)Marshal.PtrToStructure(p1, typeof(USERCMD_PARA));
                    int n = 1;
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void btn_SetModel_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            msgflyMarkCall = MsgFlyMark;
            int nRet = CSharpInterface.HS_SetMarkModel(g_uCard, m_nMarkModel, m_nFlyType, !checkBox_Pip_Revl.Checked, m_dbSpeed, 200, msgflyMarkCall);
            nRet = CSharpInterface.HS_SetCustomMsgCall(g_uCard, CustomMsgCall);
            if (nRet!=0)
            {
                ShowLastError();
            }
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        private void radioBtn_Normal_Click(object sender, EventArgs e)
        {
            m_nMarkModel = 0;
        }

        private void radioBtn_PC_Fly_Click(object sender, EventArgs e)
        {
            m_nMarkModel = 1;
        }

        private void radioBtn_IO_FLY_Click(object sender, EventArgs e)
        {
            m_nMarkModel = 2;
        }

        private void radioBtn_Cons_Speed_Click(object sender, EventArgs e)
        {
            m_nFlyType = 0;
        }

        private void radioBtn_Encoder_Click(object sender, EventArgs e)
        {
            m_nFlyType = 1;
        }

        private void radioBtn_ED_CheckedChanged(object sender, EventArgs e)
        {
            m_nFlyType = 2;
        }

        private void textBox_Length_TextChanged(object sender, EventArgs e)
        {
            m_dbSpeed = Convert.ToDouble(textBox_Length.Text);
        }

        public void MsgFlyMark(uint nCard, int nID, UInt64 nMarkTime)
        {
            if (g_uCard == nCard)
            {
                if (nID == 0)
                {
                    UInt64 nTime = nMarkTime;
                    string str = "IO FlyMark finish...! It took";
                    string strTime;
                    strTime = string.Format("%d ms", nTime);
                    //tbNote.Text = str + strTime;
                }
                else 
                {
                    //tbNote.Text = "IO FlyMark error";
                }
            }
        }


        private void btnChangeBitmapByName_Click(object sender, EventArgs e)
        {
           OpenFileDialog dialog = new OpenFileDialog();
           dialog.Multiselect = false;
           dialog.Title = "请选择文件";
           dialog.Filter = "所有文件(*.*)|*.*";
           if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
           {
               string file = dialog.FileName;
               int nRet = CSharpInterface.HS_ChangeBitmap(g_uCard
                   , tbBmpObjName.Text // 位图对象名
                   , file);           // 新位图文件完整路径
               if (nRet != 0)
               {
                   ShowLastError();
               }
               else
               {
                   Preview();
               }
           }
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void m_btnMotorMoveEx_Click(object sender, EventArgs e)
        {
            m_dbMoveValue0 = Convert.ToDouble(textBox_movement0.Text);
            m_dbMoveValue1 = Convert.ToDouble(textBox_movement1.Text);
            m_dbMoveValue2 = Convert.ToDouble(textBox_movement2.Text);
            m_dbMoveValue3 = Convert.ToDouble(textBox_movement3.Text);
            Thread motorMoveThread = new Thread(Thread_MotorMove);
            motorMoveThread.Start(this);
        }

        private void m_btnHomeMoveEx_Click(object sender, EventArgs e)
        {
            m_dbMoveValue0 = Convert.ToDouble(textBox_movement0.Text);
            m_dbMoveValue1 = Convert.ToDouble(textBox_movement1.Text);
            m_dbMoveValue2 = Convert.ToDouble(textBox_movement2.Text);
            m_dbMoveValue3 = Convert.ToDouble(textBox_movement3.Text);
            int nAxisEx = (m_bEnableAxis0 ? 1 : 0) |
              (m_bEnableAxis1 ? 1 << 1 : 0) |
              (m_bEnableAxis2 ? 1 << 2 : 0) |
              (m_bEnableAxis3 ? 1 << 3 : 0);
            int nRet = CSharpInterface.HS_HomeMoveVEx(g_uCard, nAxisEx, m_bSoftHome);
            ShowError(nRet);
        }

        private void m_btnStopRunEx_Click(object sender, EventArgs e)
        {
            m_bEnableAxis0 = checkBox_Axis0.Checked;
            m_bEnableAxis1 = checkBox_Axis1.Checked;
            m_bEnableAxis2 = checkBox_Axis2.Checked;
            m_bEnableAxis3 = checkBox_Axis3.Checked;
            int nRet = 0;
            if (m_bEnableAxis0)
                nRet = CSharpInterface.HS_StopRunEx(g_uCard, 1);
            if (m_bEnableAxis1)
                nRet = CSharpInterface.HS_StopRunEx(g_uCard, 2);
            if (m_bEnableAxis2)
                nRet = CSharpInterface.HS_StopRunEx(g_uCard, 4);
            if (m_bEnableAxis3)
                nRet = CSharpInterface.HS_StopRunEx(g_uCard, 8);
            ShowError(nRet);
        }

        private void m_btnAMove_CheckedChanged(object sender, EventArgs e)
        {
            m_nMoveModel = 0;
        }

        private void m_btnRMove_CheckedChanged(object sender, EventArgs e)
        {
            m_nMoveModel = 1;
        }

        private void m_btnMoveLoad_CheckedChanged(object sender, EventArgs e)
        {
            m_nMoveType = 0;
        }

        private void m_btnMoveIdle_CheckedChanged(object sender, EventArgs e)
        {
            m_nMoveType = 1;
        }

        private void checkBox_Axis0_CheckedChanged(object sender, EventArgs e)
        {
            m_bEnableAxis0 = checkBox_Axis0.Checked;
        }

        private void checkBox_Axis1_CheckedChanged(object sender, EventArgs e)
        {
            m_bEnableAxis1 = checkBox_Axis1.Checked;
        }

        private void checkBox_Axis2_CheckedChanged(object sender, EventArgs e)
        {
            m_bEnableAxis2 = checkBox_Axis2.Checked;
        }

        private void checkBox_Axis3_CheckedChanged(object sender, EventArgs e)
        {
            m_bEnableAxis3 = checkBox_Axis3.Checked;
        }

        private void m_btnSoftHome_CheckedChanged(object sender, EventArgs e)
        {
            // 获取触发事件的CheckBox实例
            CheckBox checkBox = sender as CheckBox;
            if (checkBox != null)
            {
                // 检查CheckBox的状态
                if (checkBox.Checked)
                {
                    m_bSoftHome = true;
                }
                else
                {
                    m_bSoftHome = false;  
                }
            }
        }

        public void ShowError(int nErrorCode)
        {
            if (nErrorCode != 0)
            {
                StringBuilder szBuff = new StringBuilder(200);
                CSharpInterface.HS_GetLastError(g_uCard, ref nErrorCode, szBuff, 200);
                tbNote.Text = szBuff.ToString();
            }
        }

        private void PictureBoxMouseDown(object sender, MouseEventArgs e)
        {
            int mouseX = e.X;
            int mouseY = e.Y;
            // 如果你想要获取相对于屏幕的坐标，可以使用控件的PointToScreen方法
            Point screenPoint = pictureBox1.PointToScreen(new Point(mouseX, mouseY));

            if (e.Button == MouseButtons.Left)
            {
                m_bBoxSelect = true;
                m_ptBoxSelectStart = screenPoint;
            }
            else if (e.Button == MouseButtons.Middle)
            {
                m_bMove = true;
                m_ptMoveStart = screenPoint;
            }
        }

        private void PictureBoxMouseMove(object sender, MouseEventArgs e)
        {
            int mouseX = e.X;
            int mouseY = e.Y;
            // 如果你想要获取相对于屏幕的坐标，可以使用控件的PointToScreen方法
            Point screenPoint = pictureBox1.PointToScreen(new Point(mouseX, mouseY));

            if (m_bBoxSelect)
            {
                if (m_ptBoxSelectStart != screenPoint)
                {
                    m_rectBoxSelect = new Rectangle(m_ptBoxSelectStart.X, m_ptBoxSelectStart.Y, Math.Abs(screenPoint.X - m_ptBoxSelectStart.X), Math.Abs(screenPoint.Y - m_ptBoxSelectStart.Y));
                    Preview();
                }
            }

            if (m_bMove && m_bInitOk)
            {
                m_dbViewX += (m_ptMoveStart.X - screenPoint.X) / (3 * m_dbViewRate);
                m_dbViewY += -(m_ptMoveStart.Y - screenPoint.Y) / (3 * m_dbViewRate);
                m_ptMoveStart = screenPoint;
                Preview();
            }
        }

        private void PictureBoxMouseUp(object sender, MouseEventArgs e)
        {
            int mouseX = e.X;
            int mouseY = e.Y;

             // 如果你想要获取相对于屏幕的坐标，可以使用控件的PointToScreen方法
            Point screenPoint = pictureBox1.PointToScreen(new Point(mouseX, mouseY));

            if (e.Button == MouseButtons.Left)
            {
                m_bBoxSelect = false;
                Rectangle rect = new Rectangle(pictureBox1.Location, pictureBox1.ClientSize);
                if ((m_ptBoxSelectStart.X - screenPoint.X == 0) && (m_ptBoxSelectStart.Y - screenPoint.Y == 0))
                {	// 点选
                    if (rect.Contains(screenPoint))
                    {
                        Point pTemp = new Point(screenPoint.X - rect.Left, screenPoint.Y - rect.Top);
                        if (0 != CSharpInterface.HS_PickObjectByPoint(g_uCard, pTemp.X, pTemp.Y, false, m_dbViewX, m_dbViewY, m_dbViewRate))
                            ShowLastError();
                    }
                }
                else
                {	// 框选
                    double dbTop = (m_ptBoxSelectStart.Y < screenPoint.Y ? m_ptBoxSelectStart.Y : screenPoint.Y) - rect.Top;
                    double dbLeft = (m_ptBoxSelectStart.X < screenPoint.X ? m_ptBoxSelectStart.X : screenPoint.X) - rect.Left;
                    double dbBottom = (m_ptBoxSelectStart.Y > screenPoint.Y ? m_ptBoxSelectStart.Y : screenPoint.Y) - rect.Top;
                    double dbRight = (m_ptBoxSelectStart.X > screenPoint.X ? m_ptBoxSelectStart.X : screenPoint.X) - rect.Left;

                    Point pTemp = new Point(screenPoint.X - rect.Left, screenPoint.Y - rect.Top);
                    if (0 != CSharpInterface.HS_PickObjectByRect(g_uCard, dbLeft, dbRight, dbTop, dbBottom, false, m_dbViewX, m_dbViewY, m_dbViewRate))
                        ShowLastError();
                }
                Preview();
            }
            else if (e.Button == MouseButtons.Middle)
            {
                m_bMove = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int nRtn = CSharpInterface.HS_SetMotionSysPara(0, 0, 10000, 360, 100, 1, 1, 360, 180, 0.5, 0.5, false, false, true);
            nRtn = CSharpInterface.HS_SetRotateMarkPara(0, 38, 10, 11, false);
            nRtn = CSharpInterface.HS_PreprocessRotateData(0, 0);
            nRtn = CSharpInterface.HS_RotateMark(0, 0, false, true, 0);
        }

        private void btnEarMarkFlyByIO_Click(object sender, EventArgs e)
        {
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            int nRet = CSharpInterface.HS_MarkFlyIOStart(g_uCard);

            ShowLastError();
            this.Cursor = System.Windows.Forms.Cursors.Arrow;
        }

        private void btnSendDelayValue_Click(object sender, EventArgs e)
        {
            double dbDelay = Convert.ToDouble(textDelayValue.Text);
            int nPulse = Convert.ToInt32(dbDelay / m_dbSpeed);

            // 下发的数据
            USERCMD_PARA cmd_down = new USERCMD_PARA();
            cmd_down.wPara = new UInt16[16];

            // 接收的数据
            USERCMD_PARA cmd_ret = new USERCMD_PARA();
            cmd_ret.wPara = new UInt16[16];

            cmd_down.wPara[0] = 6; // 固定值
            cmd_down.wPara[1] = 30301; // 命令号
            cmd_down.wPara[2] = 0; // 其他数据位
            cmd_down.wPara[3] = Convert.ToUInt16(nPulse & 0xFFFF);
            cmd_down.wPara[4] = Convert.ToUInt16((nPulse >> 16) & 0xFFFF);

            // 下发数据格式转换
            int size1 = Marshal.SizeOf(typeof(USERCMD_PARA));
            byte[] bytes1 = new byte[size1];
            IntPtr pBuff1 = Marshal.AllocHGlobal(size1);
            Marshal.StructureToPtr(cmd_down, pBuff1, true);
            Marshal.Copy(pBuff1, bytes1, 0, size1);
            Int64 p1 = pBuff1.ToInt64();

            // 接收数据格式转换
            int size2 = Marshal.SizeOf(typeof(USERCMD_PARA));
            byte[] bytes2 = new byte[size2];
            IntPtr pBuff2 = Marshal.AllocHGlobal(size2);
            Marshal.StructureToPtr(cmd_ret, pBuff2, true);
            Marshal.Copy(pBuff2, bytes2, 0, size1);
            Int64 p2 = pBuff2.ToInt64();

            // 发送自定义命令
            int ret = CSharpInterface.HS_SendCustomCmd(g_uCard, p1, p2);

            Marshal.FreeHGlobal(pBuff1);
            Marshal.FreeHGlobal(pBuff2);
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            // test
            int nRet = 0;
            FONTPARA_EX param = new FONTPARA_EX();

            param.nFontType = 0; // TTF
            param.szFontName = "微软雅黑";
            nRet = CSharpInterface.HS_SetFontPara(0, ref param);
            nRet = CSharpInterface.HS_AddText(0, "阿斯顿qwe123", 8, 50, 0, "", 0, 20, 0, 0, 0, 0, 0, "");

            param.szFontName = "Arial"; // TTF
            nRet = CSharpInterface.HS_SetFontPara(0, ref param);
            nRet = CSharpInterface.HS_AddText(0, "阿斯顿qwe123", 8, 50, 0, "", 0, 10, 0, 0, 0, 0, 0, "");

            param.nFontType = 1; // SHX
            param.szShxCN = "简体单线";
            param.szShxEN = "Romanc";
            param.szShxNum = "Txt";
            nRet = CSharpInterface.HS_SetFontPara(0, ref param);
            nRet = CSharpInterface.HS_AddText(0, "阿斯顿qwe123", 8, 50, 0, "", 0, 0, 0, 0, 0, 0, 0, "");

            param.nFontType = 2; // HANS
            param.szFontName = "HANS002";
            nRet = CSharpInterface.HS_SetFontPara(0, ref param);
            nRet = CSharpInterface.HS_AddText(0, "阿斯顿qwe123", 8, 50, 0, "", 0, -10, 0, 0, 0, 0, 0, "");

            param.nFontType = 3; // DOT
            param.szShxCN = "12*12";
            param.szShxEN = "8*16";
            nRet = CSharpInterface.HS_SetFontPara(0, ref param);
            nRet = CSharpInterface.HS_AddText(0, "阿斯顿qwe123", 8, 50, 0, "", 0, -20, 0, 0, 0, 0, 0, "");

            return;

			// test
//             LAYERPARA layPara = new LAYERPARA();
//             int ret = CSharpInterface.HS_GetLayerPara(g_uCard, 0, ref layPara);
//             layPara.dbCurrent += 1;
//             ret = CSharpInterface.HS_SetLayerPara(g_uCard, 0, ref layPara);
//             return;
        }
    }
}
