﻿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 CcanCs;

namespace CanCommunicationCallback
{
    public partial class Form1 : Form
    {
        //-----------------------------------
        // Create instance Ccan class
        //-----------------------------------
        Ccan can = new Ccan();

        //-----------------------------------
        // Macro definition
        //-----------------------------------
        public const int MAX_TRANSMIT_DATA = 8;                    // Maximum number of transmitted data
        public const int MAX_RECEIVE_MESSAGE = 100;                // Maximum number of received messages
        public const int MAX_RECEIVE_DATA = 64;                    // Maximum number of received data

        //-----------------------------------
        // Declaration of global variables
        //-----------------------------------
        public short g_id;                                         // Device ID
        public TextBox[] textBox_TransmitData = new TextBox[8];    // Transmit data controls
        public GCHandle gCh;                                       // GCHandle for callback routine
        public PCAN_EVENT_CALLBACK pdelegate_func;                 // Delegate for event notification
        public IntPtr pfunc;                                       // IntPtr for callback routine

        public Form1()
        {
            InitializeComponent();
        }

        unsafe private void Form1_Load(object sender, EventArgs e)
        {
            short data_no;

            //-----------------------------------
            // Set the default button
            //-----------------------------------
            AcceptButton = button_Exit;
            //-----------------------------------
            // Setting for control array
            //-----------------------------------
            //-----------------
            // Controls for transmit data
            //-----------------
            textBox_TransmitData[0] = textBox_TransmitData0;
            textBox_TransmitData[1] = textBox_TransmitData1;
            textBox_TransmitData[2] = textBox_TransmitData2;
            textBox_TransmitData[3] = textBox_TransmitData3;
            textBox_TransmitData[4] = textBox_TransmitData4;
            textBox_TransmitData[5] = textBox_TransmitData5;
            textBox_TransmitData[6] = textBox_TransmitData6;
            textBox_TransmitData[7] = textBox_TransmitData7;
            //-----------------------------------
            // Initializing screen display
            //-----------------------------------
            //-----------------------------------
            // Initialization
            //-----------------------------------
            textBox_DeviceName.Text = "CAN000";
            //-----------------------------------
            // Common setting value
            //-----------------------------------
            textBox_ChannelNo.Text = "0";
            //-----------------------------------
            // CAN communication setting values
            //-----------------------------------
            textBox_CanBitrate.Text = "125000";
            textBox_CanTSEG1.Text = "240";
            textBox_CanSJW.Text = "80";
            textBox_CanTSEG2.Text = "80";
            //-----------------------------------
            // CAN FD communication setting values
            //-----------------------------------
            //-----------------
            // Arbitration bitrate
            //-----------------
            textBox_CanFdArbBitrate.Text = "125000";
            textBox_CanFdArbTSEG1.Text = "240";
            textBox_CanFdArbSJW.Text = "80";
            textBox_CanFdArbTSEG2.Text = "80";
            //-----------------
            // Data bitrate
            //-----------------
            textBox_CanFdDataBitrate.Text = "1000000";
            textBox_CanFdDataTSEG1.Text = "30";
            textBox_CanFdDataSJW.Text = "10";
            textBox_CanFdDataTSEG2.Text = "10";
            //-----------------------------------
            // Acceptance target CAN ID
            //-----------------------------------
            //-----------------
            // Message type
            //-----------------
            checkBox_MessageTypeMaskCan.Checked = false;
            checkBox_MessageTypeMaskCanFd.Checked = false;
            checkBox_MessageTypeMaskRemoteFrame.Checked = false;
            checkBox_MessageTypeMaskBitrateSwitch.Checked = false;
            checkBox_MessageTypeMaskStdFormat.Checked = false;
            checkBox_MessageTypeMaskExtFormat.Checked = false;
            //-----------------
            // CAN ID
            //-----------------
            textBox_CanIdMask.Text = "1FFFFF00";
            textBox_CanIdCode.Text = "100";
            //-----------------------------------
            // Transmit
            //-----------------------------------
            //-----------------
            // Message type
            //-----------------
            checkBox_TransmitMessageTypeCan.Checked = true;
            checkBox_TransmitMessageTypeCanFd.Checked = false;
            checkBox_TransmitMessageTypeRemoteFrame.Checked = false;
            checkBox_TransmitMessageTypeBitrateSwitch.Checked = false;
            checkBox_TransmitMessageTypeExtFormat.Checked = false;
            //-----------------
            // CAN ID
            //-----------------
            textBox_TransmitCanId.Text = "100";
            //-----------------
            // Data length
            //-----------------
            comboBox_TransmitDataLength.Items.Add("0");
            comboBox_TransmitDataLength.Items.Add("1");
            comboBox_TransmitDataLength.Items.Add("2");
            comboBox_TransmitDataLength.Items.Add("3");
            comboBox_TransmitDataLength.Items.Add("4");
            comboBox_TransmitDataLength.Items.Add("5");
            comboBox_TransmitDataLength.Items.Add("6");
            comboBox_TransmitDataLength.Items.Add("7");
            comboBox_TransmitDataLength.Items.Add("8");
            comboBox_TransmitDataLength.SelectedIndex = 8;
            //-----------------
            // Data
            //-----------------
            for (data_no = 0; data_no < MAX_TRANSMIT_DATA; data_no++)
            {
                textBox_TransmitData[data_no].Text = data_no.ToString("x");
            }
            //-----------------------------------
            // Status
            //-----------------------------------
            textBox_Status.Text = "";
            textBox_TxErrorCount.Text = "0";
            textBox_RxErrorCount.Text = "0";
            //-----------------------------------
            // Return value
            //-----------------------------------
            textBox_Ret.Text = "";
            //-----------------------------------
            // Initialize the delegate for event notification
            //-----------------------------------
            pdelegate_func = new PCAN_EVENT_CALLBACK(CallBackProc);
            //-----------------------------------
            // Do not release the delegate
            //-----------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
        }

        //=========================================================
        // CanInit()
        //=========================================================
        private void button_CanInit_Click(object sender, EventArgs e)
        {
            int    ret;
            string device_name;
            string error_string;

            //-----------------------------
            // Get device name
            //-----------------------------
            device_name = textBox_DeviceName.Text;
            //-----------------------------
            // Initialization and get device ID
            //-----------------------------
            ret = can.Init(device_name, out g_id);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanSetCanTiming()
        //=========================================================
        private void button_CanSetCanTiming_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   bitrate;
            ushort tseg1;
            ushort sjw;
            ushort tseg2;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Store bitrate
            //-----------------------------
            if (uint.TryParse(textBox_CanBitrate.Text, out bitrate) == false)
            {
                bitrate = 0;
            }
            //-----------------------------
            // Store time segment 1
            //-----------------------------
            if (ushort.TryParse(textBox_CanTSEG1.Text, out tseg1) == false)
            {
                tseg1 = 0;
            }
            //-----------------------------
            // Store SJW (Synchronization Jump Width)
            //-----------------------------
            if (ushort.TryParse(textBox_CanSJW.Text, out sjw) == false)
            {
                sjw = 0;
            }
            //-----------------------------
            // Store time segment 2
            //-----------------------------
            if (ushort.TryParse(textBox_CanTSEG2.Text, out tseg2) == false)
            {
                tseg2 = 0;
            }
            //-----------------------------
            // CAN communication timing setting
            //-----------------------------
            ret = can.SetCanTiming(g_id, channel_no, bitrate, tseg1, sjw, tseg2);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanGetCanTiming()
        //=========================================================
        private void button_CanGetCanTiming_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   bitrate;
            ushort tseg1;
            ushort sjw;
            ushort tseg2;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Get CAN communication timing setting
            //-----------------------------
            ret = can.GetCanTiming(g_id, channel_no, out bitrate, out tseg1, out sjw, out tseg2);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------
            // Update bitrate display
            //-----------------------------
            textBox_CanBitrate.Text = bitrate.ToString();
            //-----------------------------
            // Update time segment 1 display
            //-----------------------------
            textBox_CanTSEG1.Text = tseg1.ToString();
            //-----------------------------
            // Update SJW (Synchronization Jump Width) display
            //-----------------------------
            textBox_CanSJW.Text = sjw.ToString();
            //-----------------------------
            // Update time segment 2 display
            //-----------------------------
            textBox_CanTSEG2.Text = tseg2.ToString();
        }

        //=========================================================
        // CanSetCanFdTiming()
        //=========================================================
        private void button_CanSetCanFdTiming_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   arb_bitrate, data_bitrate;
            ushort arb_tseg1, data_tseg1;
            ushort arb_sjw, data_sjw;
            ushort arb_tseg2, data_tseg2;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Store arbitration bitrate
            //-----------------------------
            if (uint.TryParse(textBox_CanFdArbBitrate.Text, out arb_bitrate) == false)
            {
                arb_bitrate = 0;
            }
            //-----------------------------
            // Store arbitration time segment 1
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdArbTSEG1.Text, out arb_tseg1) == false)
            {
                arb_tseg1 = 0;
            }
            //-----------------------------
            // Store arbitration SJW (Synchronization Jump Width)
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdArbSJW.Text, out arb_sjw) == false)
            {
                arb_sjw = 0;
            }
            //-----------------------------
            // Store arbitration time segment 2
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdArbTSEG2.Text, out arb_tseg2) == false)
            {
                arb_tseg2 = 0;
            }
            //-----------------------------
            // Store data bitrate
            //-----------------------------
            if (uint.TryParse(textBox_CanFdDataBitrate.Text, out data_bitrate) == false)
            {
                data_bitrate = 0;
            }
            //-----------------------------
            // Store data time segment 1
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdDataTSEG1.Text, out data_tseg1) == false)
            {
                data_tseg1 = 0;
            }
            //-----------------------------
            // Store data SJW (Synchronization Jump Width)
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdDataSJW.Text, out data_sjw) == false)
            {
                data_sjw = 0;
            }
            //-----------------------------
            // Store data time segment 2
            //-----------------------------
            if (ushort.TryParse(textBox_CanFdDataTSEG2.Text, out data_tseg2) == false)
            {
                data_tseg2 = 0;
            }
            //-----------------------------
            // CAN FD communication timing setting
            //-----------------------------
            ret = can.SetCanFdTiming(g_id, channel_no, arb_bitrate, arb_tseg1, arb_sjw, arb_tseg2, data_bitrate, data_tseg1, data_sjw, data_tseg2);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanGetCanFdTiming()
        //=========================================================
        private void button_CanGetCanFdTiming_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   arb_bitrate, data_bitrate;
            ushort arb_tseg1, data_tseg1;
            ushort arb_sjw, data_sjw;
            ushort arb_tseg2, data_tseg2;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Get CAN FD communication timing setting
            //-----------------------------
            ret = can.GetCanFdTiming(g_id, channel_no, out arb_bitrate, out arb_tseg1, out arb_sjw, out arb_tseg2, out data_bitrate, out data_tseg1, out data_sjw, out data_tseg2);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------
            // Update arbitration bitrate display
            //-----------------------------
            textBox_CanFdArbBitrate.Text = arb_bitrate.ToString();
            //-----------------------------
            // Update arbitration time segment 1 display
            //-----------------------------
            textBox_CanFdArbTSEG1.Text = arb_tseg1.ToString();
            //-----------------------------
            // Update arbitration SJW (Synchronization Jump Width) display
            //-----------------------------
            textBox_CanFdArbSJW.Text = arb_sjw.ToString();
            //-----------------------------
            // Update arbitration time segment 2 display
            //-----------------------------
            textBox_CanFdArbTSEG2.Text = arb_tseg2.ToString();
            //-----------------------------
            // Update data bitrate display
            //-----------------------------
            textBox_CanFdDataBitrate.Text = data_bitrate.ToString();
            //-----------------------------
            // Update data time segment 1 display
            //-----------------------------
            textBox_CanFdDataTSEG1.Text = data_tseg1.ToString();
            //-----------------------------
            // Update data SJW (Synchronization Jump Width) display
            //-----------------------------
            textBox_CanFdDataSJW.Text = data_sjw.ToString();
            //-----------------------------
            // Update data time segment 2 display
            //-----------------------------
            textBox_CanFdDataTSEG2.Text = data_tseg2.ToString();
        }

        //=========================================================
        // CanSetChannelAcceptance()
        //=========================================================
        private void button_CanSetChannelAcceptance_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   message_type_mask;
            uint   can_id_mask;
            uint   can_id_code;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Store receive message type mask
            //-----------------------------
            //-----------------
            // Initialization
            //-----------------
            message_type_mask = (uint)CcanConst.CCAN_MSG_TYPE_DISABLE;
            //-----------------
            // Message type CAN
            //-----------------
            if (checkBox_MessageTypeMaskCan.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_CAN;
            }
            //-----------------
            // Message type CAN FD
            //-----------------
            if (checkBox_MessageTypeMaskCanFd.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_CAN_FD;
            }
            //-----------------
            // Message type Remote frame
            //-----------------
            if (checkBox_MessageTypeMaskRemoteFrame.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_REMOTE_FRAME;
            }
            //-----------------
            // Message type Bitrate switch
            //-----------------
            if (checkBox_MessageTypeMaskBitrateSwitch.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_BITRATE_SWITCH;
            }
            //-----------------
            // Message type Standard format
            //-----------------
            if (checkBox_MessageTypeMaskStdFormat.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_STANDARD_FORMAT;
            }
            //-----------------
            // Message type Extended format
            //-----------------
            if (checkBox_MessageTypeMaskExtFormat.Checked)
            {
                message_type_mask |= (uint)CcanConst.CCAN_MSG_TYPE_EXTENDED_FORMAT;
            }
            //-----------------------------
            // Store CAN ID mask
            //-----------------------------
            try
            {
                can_id_mask = Convert.ToUInt32(textBox_CanIdMask.Text, 16);
            }
            catch
            {
                can_id_mask = 0;
            }
            //-----------------------------
            // Store CAN ID code
            //-----------------------------
            try
            {
                can_id_code = Convert.ToUInt32(textBox_CanIdCode.Text, 16);
            }
            catch
            {
                can_id_code = 0;
            }
            //-----------------------------
            // Receive acceptance setting
            //-----------------------------
            ret = can.SetChannelAcceptance(g_id, channel_no, message_type_mask, can_id_mask, can_id_code);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanGetChannelAcceptance()
        //=========================================================
        private void button_CanGetChannelAcceptance_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            uint   message_type_mask;
            uint   can_id_mask;
            uint   can_id_code;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Get receive acceptance setting
            //-----------------------------
            ret = can.GetChannelAcceptance(g_id, channel_no, out message_type_mask, out can_id_mask, out can_id_code);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------
            // Message type CAN
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_CAN) == (uint)CcanConst.CCAN_MSG_TYPE_CAN)
            {
                checkBox_MessageTypeMaskCan.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskCan.Checked = false;
            }
            //-----------------------------
            // Message type CAN FD
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_CAN_FD) == (uint)CcanConst.CCAN_MSG_TYPE_CAN_FD)
            {
                checkBox_MessageTypeMaskCanFd.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskCanFd.Checked = false;
            }
            //-----------------------------
            // Message type Remote frame
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_REMOTE_FRAME) == (uint)CcanConst.CCAN_MSG_TYPE_REMOTE_FRAME)
            {
                checkBox_MessageTypeMaskRemoteFrame.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskRemoteFrame.Checked = false;
            }
            //-----------------------------
            // Message type Bitrate switch
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_BITRATE_SWITCH) == (uint)CcanConst.CCAN_MSG_TYPE_BITRATE_SWITCH)
            {
                checkBox_MessageTypeMaskBitrateSwitch.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskBitrateSwitch.Checked = false;
            }
            //-----------------------------
            // Message type Standard format
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_STANDARD_FORMAT) == (uint)CcanConst.CCAN_MSG_TYPE_STANDARD_FORMAT)
            {
                checkBox_MessageTypeMaskStdFormat.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskStdFormat.Checked = false;
            }
            //-----------------------------
            // Message type Extended format
            //-----------------------------
            if ((message_type_mask & (uint)CcanConst.CCAN_MSG_TYPE_EXTENDED_FORMAT) == (uint)CcanConst.CCAN_MSG_TYPE_EXTENDED_FORMAT)
            {
                checkBox_MessageTypeMaskExtFormat.Checked = true;
            }
            else
            {
                checkBox_MessageTypeMaskExtFormat.Checked = false;
            }
            //-----------------------------
            // Update CAN ID mask display
            //-----------------------------
            textBox_CanIdMask.Text = string.Format("{0:X}", can_id_mask);
            //-----------------------------
            // Update CAN ID code display
            //-----------------------------
            textBox_CanIdCode.Text = string.Format("{0:X}", can_id_code);
        }

        //=========================================================
        // CanBusConnect()
        //=========================================================
        private void button_CanBusConnect_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Bus connection
            //-----------------------------
            ret = can.BusConnect(g_id, channel_no);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanBusDisconnect()
        //=========================================================
        private void button_CanBusDisconnect_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Bus disconnection
            //-----------------------------
            ret = can.BusDisconnect(g_id, channel_no);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanTransmit()
        //=========================================================
        private void button_CanTransmit_Click(object sender, EventArgs e)
        {
            int      ret;
            string   error_string;
            ushort   channel_no;
            uint     message_num;
            uint[]   message_type = new uint[1];
            uint[]   can_id = new uint[1];
            ushort[] data_length = new ushort[1];
            byte[,]  transmit_data = new byte[1, MAX_TRANSMIT_DATA];
            ushort   data_no;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Store transmit message type
            //-----------------------------
            //-----------------
            // Initialization
            //-----------------
            message_type[0] = 0;
            //-----------------
            // Message type CAN
            //-----------------
            if (checkBox_TransmitMessageTypeCan.Checked)
            {
                message_type[0] |= (uint)CcanConst.CCAN_MSG_TYPE_CAN;
            }
            //-----------------
            // Message type CAN FD
            //-----------------
            if (checkBox_TransmitMessageTypeCanFd.Checked)
            {
                message_type[0] |= (uint)CcanConst.CCAN_MSG_TYPE_CAN_FD;
            }
            //-----------------
            // Message type Remote frame
            //-----------------
            if (checkBox_TransmitMessageTypeRemoteFrame.Checked)
            {
                message_type[0] |= (uint)CcanConst.CCAN_MSG_TYPE_REMOTE_FRAME;
            }
            //-----------------
            // Message type Bitrate switch
            //-----------------
            if (checkBox_TransmitMessageTypeBitrateSwitch.Checked)
            {
                message_type[0] |= (uint)CcanConst.CCAN_MSG_TYPE_BITRATE_SWITCH;
            }
            //-----------------
            // Message type Extended format
            //-----------------
            if (checkBox_TransmitMessageTypeExtFormat.Checked)
            {
                message_type[0] |= (uint)CcanConst.CCAN_MSG_TYPE_EXTENDED_FORMAT;
            }
            //-----------------------------
            // Store CAN ID
            //-----------------------------
            try
            {
                can_id[0] = Convert.ToUInt32(textBox_TransmitCanId.Text, 16);
            }
            catch
            {
                can_id[0] = 0;
            }
            //-----------------------------
            // Number of transmit messages
            //-----------------------------
            message_num = 1;
            //-----------------------------
            // Store transmit message data length
            //-----------------------------
            if (ushort.TryParse(comboBox_TransmitDataLength.Text, out data_length[0]) == false)
            {
                data_length[0] = 0;
            }
            //-----------------------------
            // Store transmit message data
            //-----------------------------
            for (data_no = 0; data_no < data_length[0]; data_no++)
            {
                try
                {
                    transmit_data[0, data_no] = Convert.ToByte(textBox_TransmitData[data_no].Text, 16);
                }
                catch
                {
                    transmit_data[0, data_no] = 0;
                }
            }
            //-----------------------------
            // CAN / CAN FD Transmit
            //-----------------------------
            ret = can.Transmit(g_id, channel_no, message_num, message_type, can_id, data_length, transmit_data);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // Receive Start
        //=========================================================
        unsafe private void button_CanReceiveStart_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;

            //-----------------------------
            // Clear receive message list
            //-----------------------------
            listView_RecviceData.Items.Clear();
            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Get the fixed pointer of the delegate for event notification
            //-----------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //-----------------------------
            // Receive event start
            //-----------------------------
            ret = can.NotifyEvent(g_id, channel_no, (ushort)CcanConst.CCAN_EVENT_RECEIVE, pfunc, null);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // Receive Stop
        //=========================================================
        private void button_CanReceiveStop_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Receive event stop
            //-----------------------------
            ret = can.StopNotifyEvent(g_id, channel_no, (ushort)CcanConst.CCAN_EVENT_RECEIVE);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
        }

        //=========================================================
        // CanGetChannelStatus()
        //=========================================================
        private void button_CanGetChannelStatus_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;
            ushort channel_no;
            ushort channel_status;
            ushort tx_error_count;
            ushort rx_error_count;

            //-----------------------------
            // Store channel number
            //-----------------------------
            if (ushort.TryParse(textBox_ChannelNo.Text, out channel_no) == false)
            {
                channel_no = 0;
            }
            //-----------------------------
            // Get channel status
            //-----------------------------
            ret = can.GetChannelStatus(g_id, channel_no, out channel_status, out tx_error_count, out rx_error_count);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------
            // Update channel status display
            //-----------------------------
            if (channel_status == (uint)CcanConst.CCAN_CH_STATUS_ERR_ACTIVE)
            {
                textBox_Status.Text = "Error Active";
            }
            if (channel_status == (uint)CcanConst.CCAN_CH_STATUS_ERR_PASSIVE)
            {
                textBox_Status.Text = "Error Passive";
            }
            if (channel_status == (uint)CcanConst.CCAN_CH_STATUS_BUS_OFF)
            {
                textBox_Status.Text = "Bus OFF";
            }
            //-----------------------------
            // Update transmit error count display
            //-----------------------------
            textBox_TxErrorCount.Text = tx_error_count.ToString();
            //-----------------------------
            // Update receive error count display
            //-----------------------------
            textBox_RxErrorCount.Text = rx_error_count.ToString();
        }

        //=========================================================
        // CanExit
        //=========================================================
        private void button_CanExit_Click(object sender, EventArgs e)
        {
            int    ret;
            string error_string;

            //-----------------------------
            // Release the garbage collection handle of the delegate for event notification
            //-----------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            //-----------------------------
            // Exit process
            //-----------------------------
            ret = can.Exit(g_id);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
        }

        //=========================================================
        // Application termination
        //=========================================================
        private void button_Exit_Click(object sender, EventArgs e)
        {
            //-----------------------------
            // Release the garbage collection handle of the delegate for event notification
            //-----------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            //-----------------------------
            // Close dialog
            //-----------------------------
            this.Close();
        }

        //=========================================================
        // Callback function
        //=========================================================
        unsafe public void CallBackProc(short Id, int wParam, int lParam, void* Param)
        {
            int          ret;
            string       error_string;
            string       str;
            ListViewItem item;
            ushort       channel_no;
            uint         message_num;
            uint[]       message_type = new uint[MAX_RECEIVE_MESSAGE];
            uint[]       can_id = new uint[MAX_RECEIVE_MESSAGE];
            ushort[]     data_length = new ushort[MAX_RECEIVE_MESSAGE];
            byte[,]      receive_data = new byte[MAX_RECEIVE_MESSAGE, MAX_RECEIVE_DATA];
            uint[]       error_code = new uint[MAX_RECEIVE_MESSAGE];
            ulong[]      tick_count = new ulong[MAX_RECEIVE_MESSAGE];
            uint         message_count, data_count;

            //-----------------------------
            // Store channel number
            //-----------------------------
            channel_no = (ushort)lParam;
            //-----------------------------
            // Number of receive messages
            //-----------------------------
            message_num = MAX_RECEIVE_MESSAGE;
            //-----------------------------
            // CAN / CAN FD Receive
            //-----------------------------
            ret = can.Receive(g_id, channel_no, ref message_num, ref message_type, ref can_id, ref data_length, ref receive_data, ref error_code, ref tick_count);
            //-----------------------------
            // Error process
            //-----------------------------
            can.GetErrorString(ret, out error_string);
            textBox_Ret.Text = "ret = " + ret.ToString() + " : " + error_string;
            if (ret != (int)CcanConst.CAN_ERR_SUCCESS)
            {
                return;
            }
            //-----------------------------
            // Add list for each received message
            //-----------------------------
            for (message_count = 0; message_count < message_num; message_count++)
            {
                //-----------------------------
                // Add item: No.
                //-----------------------------
                item = new ListViewItem(listView_RecviceData.Items.Count.ToString());
                //-----------------------------
                // Add item: TickCount
                //-----------------------------
                item.SubItems.Add(string.Format("{0:D}", tick_count[message_count]));
                //-----------------------------
                // Add item: MessageType
                //-----------------------------
                item.SubItems.Add(string.Format("0x{0:X}", message_type[message_count]));
                //-----------------------------
                // Add item: CanId
                //-----------------------------
                item.SubItems.Add(string.Format("0x{0:X}", can_id[message_count]));
                //-----------------------------
                // Add item: DataLength
                //-----------------------------
                item.SubItems.Add(string.Format("{0:D}", data_length[message_count]));
                //-----------------------------
                // Add item: Data
                //-----------------------------
                str = "";
                for (data_count = 0; data_count < data_length[message_count]; data_count++)
                {
                    str += string.Format("{0:X2}", receive_data[message_count, data_count]);
                    if (data_count < (uint)(data_length[message_count] - 1))
                    {
                        str += ", ";
                    }
                }
                item.SubItems.Add(str);
                //-----------------------------
                // Add item: ErrorCode
                //-----------------------------
                item.SubItems.Add(string.Format("0x{0:X}", error_code[message_count]));
                //-----------------------------
                // Add item
                //-----------------------------
                listView_RecviceData.Items.Add(item);
                //-----------------------------
                // Scroll to display additional items
                //-----------------------------
                listView_RecviceData.EnsureVisible(listView_RecviceData.Items.Count - 1);
            }
        }
    }
}
