﻿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.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using CaioCs;

namespace AiSamplingInfiniteUser
{
    public partial class Form1 : Form
    {
        //----------------------------------------
        // Create instance Caio class
        //----------------------------------------
        Caio aio = new Caio();

        //----------------------------------------
        // Macro definition
        //----------------------------------------
        public const int MAX_AI_RANGE_NUM = 32;    // Maximum number of elements in analog input range array

        //----------------------------------------
        // Declaration of global variables
        //----------------------------------------
        public static short g_id;                                                                  // ID for device access
        public int []       g_sampling_buffer = null;                                              // User buffer
        public int          g_sampling_buffer_size;                                                // User buffer size
        public long         g_prev_count;                                                          // Previous position
        public long         g_prev_lap;                                                            // Previous overwrite count
        public string       g_file_name = "SamplingData.csv";                                      // Sampling data output file name
        public GCHandle     gCh;                                                                   // GCHandle for g_sampling_buffer array
        public IntPtr       pBuffer;                                                               // IntPtr for g_sampling_buffer array
        public short[]      g_ai_range = new short[MAX_AI_RANGE_NUM]{(short)CaioConst.PM10,        // +/-10V
                                                                     (short)CaioConst.PM5,         // +/-5V
                                                                     (short)CaioConst.PM25,        // +/-2.5V
                                                                     (short)CaioConst.PM125,       // +/-1.25V
                                                                     (short)CaioConst.PM1,         // +/-1V
                                                                     (short)CaioConst.PM0625,      // +/-0.625V
                                                                     (short)CaioConst.PM05,        // +/-0.5V
                                                                     (short)CaioConst.PM03125,     // +/-0.3125V
                                                                     (short)CaioConst.PM025,       // +/-0.25V
                                                                     (short)CaioConst.PM0125,      // +/-0.125V
                                                                     (short)CaioConst.PM01,        // +/-0.1V
                                                                     (short)CaioConst.PM005,       // +/-0.05V
                                                                     (short)CaioConst.PM0025,      // +/-0.025V
                                                                     (short)CaioConst.PM00125,     // +/-0.0125V
                                                                     (short)CaioConst.PM001,       // +/-0.01V
                                                                     (short)CaioConst.P10,         // 0 ~ 10V
                                                                     (short)CaioConst.P5,          // 0 ~ 5V
                                                                     (short)CaioConst.P4095,       // 0 ~ 4.095V
                                                                     (short)CaioConst.P25,         // 0 ~ 2.5V
                                                                     (short)CaioConst.P125,        // 0 ~ 1.25V
                                                                     (short)CaioConst.P1,          // 0 ~ 1V
                                                                     (short)CaioConst.P05,         // 0 ~ 0.5V
                                                                     (short)CaioConst.P025,        // 0 ~ 0.25V
                                                                     (short)CaioConst.P01,         // 0 ~ 0.1V
                                                                     (short)CaioConst.P005,        // 0 ~ 0.05V
                                                                     (short)CaioConst.P0025,       // 0 ~ 0.025V
                                                                     (short)CaioConst.P00125,      // 0 ~ 0.0125V
                                                                     (short)CaioConst.P001,        // 0 ~ 0.01V
                                                                     (short)CaioConst.P20MA,       // 0 ~ 20mA
                                                                     (short)CaioConst.P4TO20MA,    // 4 ~ 20mA
                                                                     (short)CaioConst.PM20MA,      // +/-20mA
                                                                     (short)CaioConst.P1TO5};      // 1 ~ 5V

        public Form1()
        {
            InitializeComponent();
        }

        private void AiSamplingInfiniteUser_Load(object sender, EventArgs e)
        {
            //----------------------------------------
            // Set the default button
            //----------------------------------------
            AcceptButton = button_Close;
            //----------------------------------------
            // Update the initial display of device name
            //----------------------------------------
            textBox_DeviceName.Text = "AIO000";
            //----------------------------------------
            // Create the combobox for analog input range
            //----------------------------------------
            comboBox_RangeValue.Items.Add("-10 - +10V");
            comboBox_RangeValue.Items.Add("-5 - +5V");
            comboBox_RangeValue.Items.Add("-2.5 - +2.5V");
            comboBox_RangeValue.Items.Add("-1.25 - +1.25V");
            comboBox_RangeValue.Items.Add("-1 - +1V");
            comboBox_RangeValue.Items.Add("-0.625 - +0.625V");
            comboBox_RangeValue.Items.Add("-0.5 - +0.5V");
            comboBox_RangeValue.Items.Add("-0.3125 - +0.3125V");
            comboBox_RangeValue.Items.Add("-0.25 - +0.25V");
            comboBox_RangeValue.Items.Add("-0.125 - +0.125V");
            comboBox_RangeValue.Items.Add("-0.1 - +0.1V");
            comboBox_RangeValue.Items.Add("-0.05 - +0.05V");
            comboBox_RangeValue.Items.Add("-0.025 - +0.025V");
            comboBox_RangeValue.Items.Add("-0.0125 - +0.0125V");
            comboBox_RangeValue.Items.Add("-0.01 - +0.01V");
            comboBox_RangeValue.Items.Add("0 - +10V");
            comboBox_RangeValue.Items.Add("0 - +5V");
            comboBox_RangeValue.Items.Add("0 - +4.095V");
            comboBox_RangeValue.Items.Add("0 - +2.5V");
            comboBox_RangeValue.Items.Add("0 - +1.25V");
            comboBox_RangeValue.Items.Add("0 - +1V");
            comboBox_RangeValue.Items.Add("0 - +0.5V");
            comboBox_RangeValue.Items.Add("0 - +0.25V");
            comboBox_RangeValue.Items.Add("0 - +0.1V");
            comboBox_RangeValue.Items.Add("0 - +0.05V");
            comboBox_RangeValue.Items.Add("0 - +0.025V");
            comboBox_RangeValue.Items.Add("0 - +0.0125V");
            comboBox_RangeValue.Items.Add("0 - +0.01V");
            comboBox_RangeValue.Items.Add("0 - +20mA");
            comboBox_RangeValue.Items.Add("4 - +20mA");
            comboBox_RangeValue.Items.Add("-20mA - +20mA");
            comboBox_RangeValue.Items.Add("1 - +5V");
            //----------------------------------------
            // Change the selection of analog input range combobox to 0
            //----------------------------------------
            comboBox_RangeValue.SelectedIndex = 0;
            //----------------------------------------
            // Create the combobox for analog input method
            //----------------------------------------
            comboBox_InpMethod.Items.Add("Single-end input");
            comboBox_InpMethod.Items.Add("Differential input");
            //----------------------------------------
            // Change the selection of analog input method combobox to 0
            //----------------------------------------
            comboBox_InpMethod.SelectedIndex = 0;
            //----------------------------------------
            // Update the initial display of number of channels for analog input
            //----------------------------------------
            textBox_ChNum.Text = "1";
            //----------------------------------------
            // Update the initial display of the sampling times
            //----------------------------------------
            textBox_SamplingTimes.Text = "2000";
            //----------------------------------------
            // Update the initial display of the data transfer times
            //----------------------------------------
            textBox_TransferTimes.Text = "1000";
            //----------------------------------------
            // Initialize global variables
            //----------------------------------------
            g_id                   = 0;
            g_sampling_buffer_size = 0;
        }

        //================================================================================
        // It is the process when the AioInit button is clicked
        // Initialize the device
        //================================================================================
        private void button_AioInit_Click(object sender, EventArgs e)
        {
            string device_name;     // Device name
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Get device name from textbox
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // Device initialization
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.Init(device_name, out g_id);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.Init = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioResetDevice button is clicked
        // Reset the device
        //================================================================================
        private void button_AioResetDev_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Reset device
            //----------------------------------------
            ret = aio.ResetDevice(g_id);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.ResetDevice = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAiRangeAll button is clicked
        // Set the input range of analog input
        //================================================================================
        private void button_SetAiRangeAll_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code
            int    index;           // Index of combobox

            //----------------------------------------
            // Update GUI information
            //----------------------------------------
            this.Refresh();
            //----------------------------------------
            // Get the index of range setting value from combobox
            //----------------------------------------
            index = comboBox_RangeValue.SelectedIndex;
            //----------------------------------------
            // Set the analog input range (all channels)
            //----------------------------------------
            ret = aio.SetAiRangeAll(g_id, g_ai_range[index]);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAiRangeAll = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAiInputMethod button is clicked
        // Set the input method of analog input
        //================================================================================
        private void button_SetAiInpMethod_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code
            int    input_method;    // Input method

            //----------------------------------------
            // Update GUI information
            //----------------------------------------
            this.Refresh();
            //----------------------------------------
            // Get the index of input method setting value from combobox
            //----------------------------------------
            input_method = comboBox_InpMethod.SelectedIndex;
            //----------------------------------------
            // Set the analog input method
            //----------------------------------------
            ret = aio.SetAiInputMethod(g_id, (short)input_method);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAiInputMethod = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the AioSetAiChannels button is clicked
        // Set the number of analog input channels used for sampling
        //================================================================================
        private void button_SetAiChannels_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code
            short  ai_channels;     // Number of channels

            //----------------------------------------
            // Get the number of channels from textbox
            //----------------------------------------
            if (short.TryParse(textBox_ChNum.Text, out ai_channels) == false)
            {
                ai_channels = 1;
            }
            //----------------------------------------
            // Set the number of channels for the analog input conversion.
            //----------------------------------------
            ret = aio.SetAiChannels(g_id, ai_channels);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAiChannels = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the Condition Set button is clicked
        // Open the condition setting dialog
        //================================================================================
        private void button_ConditionSettings_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Open the condition setting dialog
            //----------------------------------------
            Condition condition_dlg = new Condition();
            if (condition_dlg.ShowDialog() == DialogResult.OK)
            {
                //----------------------------------------
                // Set the event factor to 'Event that AD conversion start', 'Event that device operation end',
                // 'Event that the specified number of data are transferred', 'Event that overflow',
                // 'Event that sampling clock error', and 'Event that AD conversion error'.
                // Caution for modify this function (if modified, the application may not work)
                //----------------------------------------
                ret = aio.SetAiEvent(g_id, Handle, (int)(CaioConst.AIE_START | CaioConst.AIE_END | CaioConst.AIE_DATA_TSF | CaioConst.AIE_OFERR | CaioConst.AIE_SCERR | CaioConst.AIE_ADERR));
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Condition Set: aio.SetAiEvent = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display the message that condition setting is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Condition Set: Successful completion";
            }
            condition_dlg.Dispose();
        }

        //================================================================================
        // It is the process when the User Buffer Size Set button is clicked
        // Set the user buffer that stores the conversion data
        //================================================================================
        private void button_UserBufferSettings_Click(object sender, EventArgs e)
        {
            string error_string;      // Error code string
            int    ret;               // For return code
            short  data_size;         // Data size (Number of packets)
            long   sampling_times;    // Sampling times

            //----------------------------------------
            // Set the analog input conversion data transfer mode to user buffer mode
            // Caution for modify this function (if modified, the application may not work)
            //----------------------------------------
            ret = aio.SetAiTransferMode(g_id, 1);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Size Set: aio.SetAiTransferMode = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // When the user buffer mode is used to transfer data, retrieves data size that is necessary for one sampling
            //----------------------------------------
            ret = aio.GetAiSamplingDataSize(g_id, out data_size);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Size Set: aio.GetAiSamplingDataSize = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Get the sampling times from textbox
            //----------------------------------------
            if (long.TryParse(textBox_SamplingTimes.Text, out sampling_times) == false)
            {
                sampling_times = 2000;
            }
            //----------------------------------------
            // Allocate the user buffer for storing conversion data
            //----------------------------------------
            if (g_sampling_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_sampling_buffer = null;
            }
            //--------------------
            // User buffer size: number of packets that is necessary for one sampling x sampling times
            //--------------------
            g_sampling_buffer_size = (int)(data_size * sampling_times);
            try
            {
                g_sampling_buffer = new int[g_sampling_buffer_size];
            }
            catch
            {
                textBox_ReturnCode.Text = "User Buffer Size Set: Failed to allocate the user buffer";
                return;
            }
            //----------------------------------------
            // Specify Pinned handle to g_sampling_buffer
            //----------------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(g_sampling_buffer, GCHandleType.Pinned);
            }
            //----------------------------------------
            // Get address object by Pinned handle
            //----------------------------------------
            pBuffer = gCh.AddrOfPinnedObject();
            //----------------------------------------
            // Set user buffer
            //----------------------------------------
            ret = aio.SetAiTransferData(g_id, g_sampling_buffer_size, pBuffer);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "User Buffer Size Set: aio.SetAiTransferData = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display the message that user buffer setting is completed
            //----------------------------------------
            textBox_ReturnCode.Text = "User Buffer Size Set: Successful completion";
        }

        //================================================================================
        // It is the process when the AioSetAiEventTransferTimes button is clicked
        // Set the sampling times when "Event that the specified number of data are transferred" is used
        //================================================================================
        private void button_SetAiEventTransferTimes_Click(object sender, EventArgs e)
        {
            string error_string;      // Error code string
            int    ret;               // For return code
            int    transfer_times;    // Data transfer times

            //----------------------------------------
            // Get the data transfer times from textbox
            //----------------------------------------
            if (int.TryParse(textBox_TransferTimes.Text, out transfer_times) == false)
            {
                transfer_times = 1000;
            }
            //----------------------------------------
            // Set the sampling times when "Event that the specified number of data are transferred" is used
            //----------------------------------------
            ret = aio.SetAiEventTransferTimes(g_id, transfer_times);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.SetAiEventTransferTimes = " + ret.ToString() + " : " + error_string;
        }

        //================================================================================
        // It is the process when the Sampling Start button is clicked
        // After clearing the memory and status, start sampling.
        //================================================================================
        private void button_SamplingStart_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            string text_string;     // For updating the textbox
            int    ret;             // For return code
            int    ai_status;       // Analog input status

            //----------------------------------------
            // Clear status
            //----------------------------------------
            ret = aio.ResetAiStatus(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Sampling Start: aio.ResetAiStatus = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Initialize the transfer count
            //----------------------------------------
            g_prev_count = 0;
            g_prev_lap   = 0;
            //----------------------------------------
            // Delete the data file
            //----------------------------------------
            File.Delete(g_file_name);
            //----------------------------------------
            // Start sampling
            //----------------------------------------
            ret = aio.StartAi(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Sampling Start: aio.StartAi = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Get status
            //----------------------------------------
            ret = aio.GetAiStatus(g_id, out ai_status);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Sampling Start: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display status
            //----------------------------------------
            text_string = string.Format("{0:x8}H (", ai_status);
            //--------------------
            // When status 'Device is running' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
            {
                text_string += "Operating";
            }
            //--------------------
            // When status 'Device is running' is OFF
            //--------------------
            else
            {
                text_string += "Stop";
            }
            //--------------------
            // When status 'Wait the start trigger' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
            {
                text_string += ", Wait the start trigger";
            }
            //--------------------
            // When status 'The specified number of data are stored' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
            {
                text_string += ", The specified number of data are stored";
            }
            //--------------------
            // When status 'Overflow' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
            {
                text_string += ", Overflow";
            }
            //--------------------
            // When status 'Sampling clock error' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
            {
                text_string += ", Sampling clock error";
            }
            //--------------------
            // When status 'AD conversion error' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
            {
                text_string += ", AD conversion error";
            }
            //--------------------
            // When status 'Driver spec error' is ON
            //--------------------
            if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
            {
                text_string += ", Driver spec error";
            }
            text_string += ")";
            textBox_Status.Text = text_string;
            //----------------------------------------
            // Update the transfer count
            //----------------------------------------
            textBox_TotalSamplingPosition.Text = "0";
            //----------------------------------------
            // Update the overwrite count
            //----------------------------------------
            textBox_OverwriteCount.Text = "0";
            //----------------------------------------
            // Display the message that sampling start is completed
            //----------------------------------------
            textBox_ReturnCode.Text = "Sampling Start: Successful completion";
        }

        //================================================================================
        // It is the process when the AioGetAiTransferCount button is clicked
        // Get the transfer count and display it on the dialog
        //================================================================================
        private void button_GetAiTransferCount_Click(object sender, EventArgs e)
        {
            string error_string;         // Error code string
            int    ret;                  // For return code
            int    ai_transfer_count;    // Transfer count

            //----------------------------------------
            // Get the number of data that are transferred from the user memory
            //----------------------------------------
            ret = aio.GetAiTransferCount(g_id, out ai_transfer_count);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.GetAiTransferCount = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // When the transfer count acquisition function is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update the transfer count
                //--------------------
                textBox_TotalSamplingPosition.Text = ai_transfer_count.ToString();
            }
        }

        //================================================================================
        // It is the process when the AioGetAiTransferLap button is clicked
        // Get the overwrite count and display it on the dialog
        //================================================================================
        private void button_GetAiTransferLap_Click(object sender, EventArgs e)
        {
            string error_string;       // Error code string
            int    ret;                // For return code
            int    ai_transfer_lap;    // Overwrite count

            //----------------------------------------
            // Get the number of overwrite if the user buffer is used in "Overwrite the memory"
            //----------------------------------------
            ret = aio.GetAiTransferLap(g_id, out ai_transfer_lap);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.GetAiTransferLap = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // When the overwrite count acquisition function is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update the overwrite count
                //--------------------
                textBox_OverwriteCount.Text = ai_transfer_lap.ToString();
            }
        }

        //================================================================================
        // It is the process when the AioGetAiStatus button is clicked
        // Get the analog input status and display it on the dialog
        //================================================================================
        private void button_GetAiStatus_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            string text_string;     // For updating the textbox
            int    ret;             // For return code
            int    ai_status;       // Analog input status

            //----------------------------------------
            // Get status
            //----------------------------------------
            ret = aio.GetAiStatus(g_id, out ai_status);
            //----------------------------------------
            // Get error string 
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // When the status acquisition function is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
            }
        }

        //================================================================================
        // It is the process when the Sampling Stop button is clicked
        // Stop sampling
        //================================================================================
        private void button_SamplingStop_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Stop sampling
            //----------------------------------------
            ret = aio.StopAi(g_id);
            //----------------------------------------
            // Error process
            //----------------------------------------
            if (ret != 0)
            {
                //--------------------
                // Get error string 
                //--------------------
                aio.GetErrorString(ret, out error_string);
                //--------------------
                // Display message
                //--------------------
                textBox_ReturnCode.Text = "Sampling Stop: aio.StopAi = " + ret.ToString() + " : " + error_string;
                return;
            }
            //----------------------------------------
            // Display the message that sampling stop is completed
            //----------------------------------------
            textBox_ReturnCode.Text = "Sampling Stop: Successful completion";
        }

        //================================================================================
        // It is the process when the AioExit button is clicked
        // Perform the exit process of device
        //================================================================================
        private void button_AioExit_Click(object sender, EventArgs e)
        {
            string error_string;    // Error code string
            int    ret;             // For return code

            //----------------------------------------
            // Exit process
            //----------------------------------------
            ret = aio.Exit(g_id);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            aio.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display message
            //----------------------------------------
            textBox_ReturnCode.Text = "aio.Exit = " + ret.ToString() + " : " + error_string;
            //----------------------------------------
            // Release the user buffer for storing conversion data
            //----------------------------------------
            if (g_sampling_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_sampling_buffer = null;
            }
        }

        //================================================================================
        // It is the process when the Close button is clicked
        // Perform the exit process of device and terminate the application
        //================================================================================
        private void button_Close_Click(object sender, EventArgs e)
        {
            //----------------------------------------
            // Exit process
            //----------------------------------------
            aio.Exit(g_id);
            //----------------------------------------
            // Release the user buffer for storing conversion data
            //----------------------------------------
            if (g_sampling_buffer != null)
            {
                //----------------------------------------
                // GCHandle free
                //----------------------------------------
                if (gCh.IsAllocated == true)
                {
                    gCh.Free();
                }
                g_sampling_buffer = null;
            }
            //----------------------------------------
            // Close dialog
            //----------------------------------------
            this.Close();
        }

        //================================================================================
        // Operation when event occurred
        // Process for each event occurred
        //================================================================================
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override void WndProc(ref Message m)
        {
            string       error_string;         // Error code string
            string       text_string;          // For updating the textbox
            int          ret;                  // For return code
            int          ai_transfer_count;    // Transfer count
            int          ai_transfer_lap;      // Overwrite count
            int          ai_status;            // Status
            StreamWriter fp;                   // File pointer
            long         i;                    // Loop count

            //----------------------------------------
            // Event that AD conversion start
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_START)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Event that AD conversion start Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Event that AD conversion start Process: Successful completion";
            }
            //----------------------------------------
            // Event that the specified number of data are transferred
            // Acquire and display data
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_DATA_TSF)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio. GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Get the number of data that are transferred from the user memory
                //----------------------------------------
                ret = aio.GetAiTransferCount(g_id, out ai_transfer_count);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: aio.GetAiTransferCount = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Update the transfer count
                //----------------------------------------
                textBox_TotalSamplingPosition.Text = ai_transfer_count.ToString();
                //----------------------------------------
                // Get the number of overwrite if the user buffer is used in "Overwrite the memory"
                //----------------------------------------
                ret = aio.GetAiTransferLap(g_id, out ai_transfer_lap);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: aio.GetAiTransferLap = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Update the overwrite count
                //----------------------------------------
                textBox_OverwriteCount.Text = ai_transfer_lap.ToString();
                //----------------------------------------
                // Check overrun error
                //----------------------------------------
                if ((ai_transfer_lap - g_prev_lap >= 2) || ((ai_transfer_lap - g_prev_lap == 1) && (ai_transfer_count >= g_prev_count)))
                {
                    textBox_ReturnCode.Text = string.Format("Event that the specified number of data are transferred Process: Overrun Error!(count = {0:D})", (g_sampling_buffer_size * ai_transfer_lap) + ai_transfer_count);
                    return;
                }
                //----------------------------------------
                // Output sampling data to file
                //----------------------------------------
                //--------------------
                // Open file
                //--------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: File.AppendText = file open error.";
                    return;
                }
                //--------------------
                // If the transfer position is greater than the previous position
                //--------------------
                if (ai_transfer_count > g_prev_count)
                {
                    //--------------------
                    // Repeat the process from the previous position to the transfer position
                    //--------------------
                    for (i = g_prev_count; i < ai_transfer_count; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * ai_transfer_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                }
                //--------------------
                // If the transfer position is smaller than the previous position
                //--------------------
                else
                {
                    //--------------------
                    // Repeat process from previous position to user buffer size
                    //--------------------
                    for (i = g_prev_count; i < g_sampling_buffer_size; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * g_prev_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                    //--------------------
                    // Repeat the process from 0 to transfer position
                    //--------------------
                    for (i = 0; i < ai_transfer_count; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * ai_transfer_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                }
                //--------------------
                // Close file
                //--------------------
                fp.Close();
                //----------------------------------------
                // Update previous position
                //----------------------------------------
                g_prev_count = ai_transfer_count;
                g_prev_lap   = ai_transfer_lap;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Event that the specified number of data are transferred Process: Successful completion";
            }
            //----------------------------------------
            // Event that device operation end
            // Acquire and display data
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_END)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Device Operation End Event Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Get the number of data that are transferred from the user memory
                //----------------------------------------
                ret = aio.GetAiTransferCount(g_id, out ai_transfer_count);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Device Operation End Event Process: aio.GetAiTransferCount = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Update the transfer count
                //----------------------------------------
                textBox_TotalSamplingPosition.Text = ai_transfer_count.ToString();
                //----------------------------------------
                // Get the number of overwrite if the user buffer is used in "Overwrite the memory"
                //----------------------------------------
                ret = aio.GetAiTransferLap(g_id, out ai_transfer_lap);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Device Operation End Event Process: aio.GetAiTransferLap = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Update the overwrite count
                //----------------------------------------
                textBox_OverwriteCount.Text = ai_transfer_lap.ToString();
                //----------------------------------------
                // Check overrun error
                //----------------------------------------
                if ((ai_transfer_lap - g_prev_lap >= 2) || ((ai_transfer_lap - g_prev_lap == 1) && (ai_transfer_count >= g_prev_count)))
                {
                    textBox_ReturnCode.Text = string.Format("Device Operation End Event Process: Overrun Error!(count = {0:D})", (g_sampling_buffer_size * ai_transfer_lap) + ai_transfer_count);
                    return;
                }
                //----------------------------------------
                // Output sampling data to file
                //----------------------------------------
                //--------------------
                // Open file
                //--------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    textBox_ReturnCode.Text = "Device Operation End Event Process: File.AppendText = file open error.";
                    return;
                }
                //--------------------
                // If the transfer position is greater than the previous position
                //--------------------
                if (ai_transfer_count > g_prev_count)
                {
                    //--------------------
                    // Repeat the process from the previous position to the transfer position
                    //--------------------
                    for (i = g_prev_count; i < ai_transfer_count; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * ai_transfer_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Device Operation End Event Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                }
                //--------------------
                // If the transfer position is smaller than the previous position
                //--------------------
                else
                {
                    //--------------------
                    // Repeat process from previous position to user buffer size
                    //--------------------
                    for (i = g_prev_count; i < g_sampling_buffer_size; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * g_prev_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Device Operation End Event Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                    //--------------------
                    // Repeat the process from 0 to transfer position
                    //--------------------
                    for (i = 0; i < ai_transfer_count; i++)
                    {
                        text_string = "";
                        //--------------------
                        // Generate display string
                        //--------------------
                        text_string += string.Format("{0,5},", (i + 1) + (g_sampling_buffer_size * ai_transfer_lap));
                        text_string += string.Format(" {0:X8}\r\n", g_sampling_buffer[i]);
                        //--------------------
                        // Write data
                        //--------------------
                        try
                        {
                            fp.Write(text_string);
                        }
                        catch
                        {
                            textBox_ReturnCode.Text = "Device Operation End Event Process: fp.Write = file write error.";
                            fp.Close();
                            return;
                        }
                    }
                }
                //--------------------
                // Close file
                //--------------------
                fp.Close();
                //----------------------------------------
                // Update previous position
                //----------------------------------------
                g_prev_count = ai_transfer_count;
                g_prev_lap   = ai_transfer_lap;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Device Operation End Event Process: Successful completion";
            }
            //----------------------------------------
            // Event that overflow
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_OFERR)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string 
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Overflow Occurrence Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Overflow Occurrence Process: Successful completion";
            }
            //----------------------------------------
            // Event that sampling clock error
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_SCERR)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string 
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "Sampling Clock Error Occurrence Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "Sampling Clock Error Occurrence Process: Successful completion";
            }
            //----------------------------------------
            // Event that AD conversion error
            // Display the status
            //----------------------------------------
            if (m.Msg == (int)CaioConst.AIOM_AIE_ADERR)
            {
                //----------------------------------------
                // Get status
                //----------------------------------------
                ret = aio.GetAiStatus(g_id, out ai_status);
                //----------------------------------------
                // Error process
                //----------------------------------------
                if (ret != 0)
                {
                    //--------------------
                    // Get error string 
                    //--------------------
                    aio.GetErrorString(ret, out error_string);
                    //--------------------
                    // Display message
                    //--------------------
                    textBox_ReturnCode.Text = "AD Conversion Error Occurrence Process: aio.GetAiStatus = " + ret.ToString() + " : " + error_string;
                    return;
                }
                //----------------------------------------
                // Display status
                //----------------------------------------
                text_string = string.Format("{0:x8}H (", ai_status);
                //--------------------
                // When status 'Device is running' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_BUSY) == (int)CaioConst.AIS_BUSY)
                {
                    text_string += "Operating";
                }
                //--------------------
                // When status 'Device is running' is OFF
                //--------------------
                else
                {
                    text_string += "Stop";
                }
                //--------------------
                // When status 'Wait the start trigger' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_START_TRG) == (int)CaioConst.AIS_START_TRG)
                {
                    text_string += ", Wait the start trigger";
                }
                //--------------------
                // When status 'The specified number of data are stored' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DATA_NUM) == (int)CaioConst.AIS_DATA_NUM)
                {
                    text_string += ", The specified number of data are stored";
                }
                //--------------------
                // When status 'Overflow' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_OFERR) == (int)CaioConst.AIS_OFERR)
                {
                    text_string += ", Overflow";
                }
                //--------------------
                // When status 'Sampling clock error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_SCERR) == (int)CaioConst.AIS_SCERR)
                {
                    text_string += ", Sampling clock error";
                }
                //--------------------
                // When status 'AD conversion error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_AIERR) == (int)CaioConst.AIS_AIERR)
                {
                    text_string += ", AD conversion error";
                }
                //--------------------
                // When status 'Driver spec error' is ON
                //--------------------
                if ((ai_status & (int)CaioConst.AIS_DRVERR) == (int)CaioConst.AIS_DRVERR)
                {
                    text_string += ", Driver spec error";
                }
                text_string += ")";
                textBox_Status.Text = text_string;
                //----------------------------------------
                // Display the message that event processing is completed
                //----------------------------------------
                textBox_ReturnCode.Text = "AD Conversion Error Occurrence Process: Successful completion";
            }
            base.WndProc(ref m);
        }
    }
}
