﻿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.IO;
using CLoggerCs;

namespace ApiBasicLogger
{
    public partial class ApiBasicLogger : Form
    {
        //----------------------------------------
        // クラスCLoggerインスタンス作成
        //----------------------------------------
        CLogger logger = new CLogger();

        //----------------------------------------
        // グローバル変数の宣言
        //----------------------------------------
        public short                g_appid;                                // アプリアクセス用ID
        public GCHandle             gCh;                                    // コールバックルーチン用GCHandle
        public PLOGGEREVENTCALLBACK pdelegate_func;                         // イベント通知用デリゲート
        public IntPtr               pfunc;                                  // コールバックルーチン用IntPtr
        public ulong                g_samplingdata;                         // サンプリングデータ番号
        public string               g_file_name;                            // サンプリングデータ出力ファイル名
        public ushort               SequenceNum;		                    // シーケンス数

        public ApiBasicLogger()
        {
            InitializeComponent();
        }

        //================================================================================
        // 初期設定
        //================================================================================
        unsafe private void Form1_Load(object sender, EventArgs e)
        {
            //----------------------------------------
            // デバイス名の初期表示を更新
            //----------------------------------------
            textBox_DeviceName.Text = "AIO000";
            //----------------------------------------
            // 画面サイズコンボボックスの作成
            //----------------------------------------
            comboBox_WindowSize.Items.Add("最小化");
            comboBox_WindowSize.Items.Add("通常");
            comboBox_WindowSize.Items.Add("最大化");
            //----------------------------------------
            // 画面サイズ用コンボボックスの選択を最小化に変更
            //----------------------------------------
            comboBox_WindowSize.SelectedIndex = (int)CLoggerConst.LOGGER_PARAM_WINDOW_OFF;
            //----------------------------------------
            //グローバル変数の初期化
            //----------------------------------------
            g_appid = 0;
            g_file_name = "SamplingData.csv";
            g_samplingdata = 1;
            SequenceNum = 1;
            //----------------------------------------
            // イベント通知用デリゲート初期化
            //----------------------------------------
            pdelegate_func = new PLOGGEREVENTCALLBACK(CallBackProc);
            //----------------------------------------
            // デリゲートが開放されないように設定します。
            //----------------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
            return;
        }

        //================================================================================
        // LoggerOpenApplicationボタンをクリックした際の処理になります
        // アプリを起動し、アクセスを可能にします。
        //================================================================================
        private void button_LoggerOpenApplication_Click(object sender, EventArgs e)
        {
            string  device_name;     // デバイス名
            ushort  openmode;        // 画面サイズ
            int     ret;             // 戻り値取得用
            string  error_string;    // エラーコード文字列

            //----------------------------------------
            // テキストボックスからデバイス名を取得
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // コンボボックスから画面サイズを取得
            //----------------------------------------
            openmode = (ushort)comboBox_WindowSize.SelectedIndex;
            //----------------------------------------
            // アプリの初期化処理を行う
            //----------------------------------------
            ret = logger.OpenApplication(device_name, out g_appid, openmode);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerOpenApplication = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // LoggerSetDeviceNameボタンをクリックした際の処理になります
        // デバイス名の設定を行います
        //================================================================================
        private void button_LoggerSetDeviceName_Click(object sender, EventArgs e)
        {
            string  device_name;     // デバイス名
            int     ret;             // 戻り値取得用
            string  error_string;    // エラーコード文字列

            //----------------------------------------
            // テキストボックスからデバイス名を取得
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // デバイス名の設定
            //----------------------------------------
            ret = logger.SetDeviceName(g_appid, device_name);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerSetDeviceName = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // ...ボタンをクリックした際の処理になります 
        // 設定ファイルを選択するダイアログを表示します
        //================================================================================
        private void button_SelectImportSettingFile_Click(object sender, EventArgs e)
        {
            //----------------------------------------
            // ファイル名が存在するかどうかをチェックしない
            //----------------------------------------
            openFileDialog1.CheckFileExists = false;
            //----------------------------------------
            // ファイルのパスが存在する場合は、ファイルのパスをダイアログの初期パスに設定します
            //----------------------------------------
            if (textBox_SelectImportSettingFile.Text.Length > 0)
            {
                openFileDialog1.InitialDirectory    = textBox_SelectImportSettingFile.Text;
                openFileDialog1.FileName            = openFileDialog1.SafeFileName;
            }
            //----------------------------------------
            // ファイルのパスが存在しない場合は、MyDocumentsをダイアログの初期パスに設定します
            //----------------------------------------
            else
            {
                openFileDialog1.InitialDirectory    = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                openFileDialog1.FileName            = "";
            }
            //----------------------------------------
            // 選択したパスを表示
            //----------------------------------------
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox_SelectImportSettingFile.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName);
            }
            return;
        }

        //================================================================================
        // LoggerImportSettingFileボタンをクリックした際の処理になります
        // 設定内容のファイル読み込みを行います
        //================================================================================
         private void button_LoggerImportSettingFile_Click(object sender, EventArgs e)
        {
            string  filepath;        // ファイルパス
            int     ret;             // 戻り値取得用
            string  error_string;    // エラーコード文字列
            uint    status;          // ステータス格納用              

            //----------------------------------------
            // テキストボックスから設定ファイルパスを取得
            //----------------------------------------
            filepath = textBox_SelectImportSettingFile.Text;
            //----------------------------------------
            // 設定ファイルの読み出しを行う
            //----------------------------------------
            ret = logger.ImportSettingFile(g_appid, filepath, out status);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerImportSettingFile = {0} : {1} \r\nstatus=0x{2:X16}", ret, error_string, status);
            return;
        }

        //================================================================================
        // LoggerSetEventSamplingTimesボタンをクリックした際の処理になります
        // 指定サンプリング回数の設定を行います
        //================================================================================
        private void button_LoggerSetEventSamplingTimes_Click(object sender, EventArgs e)
        {
            int     ret;             // 戻り値取得用
            string  error_string;    // エラーコード文字列
            uint    sampling_times;  //指定サンプリング回数格納用

            //----------------------------------------
            // テキストボックスから指定サンプリング回数を取得
            //----------------------------------------
            if (uint.TryParse(textBox_SamplingTimes.Text, out sampling_times) == false)
            {
                sampling_times = 1000;
            }
            //----------------------------------------
            // 指定サンプリング回数の設定
            //----------------------------------------
            ret = logger.SetEventSamplingTimes(g_appid, sampling_times);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerSetEventSamplingTimes = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // LoggerGetEventSamplingTimesボタンをクリックした際の処理になります
        // 指定サンプリング回数の取得を行います
        //================================================================================
        private void button_LoggerGetEventSamplingTimes_Click(object sender, EventArgs e)
        {
            string  error_string;         // エラーコード文字列
            int     ret;                  // 戻り値取得用
            uint    sampling_times;       // 指定サンプリング回数格納用

            //----------------------------------------
            // 指定サンプリング回数を取得
            //----------------------------------------
            ret = logger.GetEventSamplingTimes(g_appid, out sampling_times);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // メッセージ表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetEventSamplingTimes = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // 指定サンプリング回数取得関数が正常終了した場合
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // サンプリング回数を更新
                //--------------------
                textBox_SamplingTimes.Text = sampling_times.ToString();
            }
            return;
        }

        //================================================================================
        // 収集開始ボタンをクリックした際の処理になります
        // アプリの入出力を開始します
        //================================================================================
        unsafe private void button_LoggerStartOperation_Click(object sender, EventArgs e)
        {

            string      error_string;                   // エラーコード文字列
            int         ret;                            // 戻り値取得用
            uint        status;                         // ステータス格納用
            ushort      InputType;                      // 入力方式
            ushort[]    ChannelNo = new ushort[256];    // チャネル番号
            byte[]      ChName = new byte[256*256];     // チャネル名
            ushort[]    Range = new ushort[256];        // レンジ
            ushort      pre_sequence = 256;             // シーケンス数

            //----------------------------------------
            // ファイルを閉じる
            //----------------------------------------
            ret = logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // メッセージ表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGraphWindowOperation = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // ファイルを削除
            //----------------------------------------
            if (File.Exists(g_file_name))
            {
                try
                {
                    File.Delete(g_file_name);
                }
                catch
                {
                    textBox_ReturnNum.Text = string.Format("データファイル削除エラー");
                    return;
                }
            }
            //----------------------------------------
            // チャネル設定取得
            //----------------------------------------
            ret = logger.GetChannelSetting(g_appid, out InputType, ref pre_sequence, ChannelNo, ChName, Range);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // エラーコード,メッセージを表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGetChannelSetting = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // サンプリングデータ数初期化
            //----------------------------------------
            g_samplingdata = 1;
            //----------------------------------------
            // バッファのモードを指定(API取得モード)
            //----------------------------------------
            ret = logger.SetAcquiredMode(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_MODE_API);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // メッセージ表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerSetAcquiredMode = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // イベント通知用デリゲートの固定ポインタを取得
            //----------------------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //----------------------------------------
            // イベント設定
            //----------------------------------------
            ret = logger.SetNotifyEvent(g_appid, pfunc, (uint)CLoggerConst.LOGGER_PARAM_EVENT_DATANUM | (uint)CLoggerConst.LOGGER_PARAM_EVENT_END, null);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // メッセージ表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerSetNotifyEvent = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // シーケンス番号をグローバル変数に入れる
            //----------------------------------------
            SequenceNum = pre_sequence;
            //----------------------------------------
            // アプリの入出力を開始
            //----------------------------------------
            ret = logger.StartOperation(g_appid, out status);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // メッセージ表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerStartOperation = {0} : {1} \r\nstatus = {2}", ret, error_string, status);
            return;
        }

        //================================================================================
        // LoggerGetTotalSamplingCountボタンをクリックした際の処理になります
        // 総サンプリング数の取得を行います
        //================================================================================
        private void button_LoggerGetTotalSamplingCount_Click(object sender, EventArgs e)
        {
            string  error_string;         // エラーコード文字列
            int     ret;                  // 戻り値取得用
            uint    sampling_count = 0;   // 総サンプリング数

            //----------------------------------------
            // 指定サンプリング回数を取得
            //----------------------------------------
            ret = logger.GetTotalSamplingCount(g_appid, out sampling_count);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // メッセージ表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetTotalSamplingCount = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // 指定サンプリング回数取得関数が正常終了した場合
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // サンプリング回数を更新
                //--------------------
                textBox_TotalSamplingCount.Text = sampling_count.ToString();
            }
            return;
        }

        //================================================================================
        // LoggerGetStoredSamplingCountボタンをクリックした際の処理になります
        // サンプリング数の取得を行います
        //================================================================================
        private void button_LoggerGetStoredSamplingCount_Click(object sender, EventArgs e)
        {
            string  error_string;               // エラーコード文字列
            int     ret;                        // 戻り値取得用
            uint    stored_sampling_count = 0;  // サンプリング数

            //----------------------------------------
            // サンプリング回数を取得
            //----------------------------------------
            ret = logger.GetStoredSamplingCount(g_appid, out stored_sampling_count);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // メッセージ表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // 指定サンプリング回数取得関数が正常終了した場合
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // サンプリング回数を更新
                //--------------------
                textBox_StoredSamplingCount.Text = stored_sampling_count.ToString();
            }
            return;
        }

        //================================================================================
        // LoggerGetApplicationStatusボタンをクリックした際の処理になります
        // デバイスのステータスの取得を行います
        //================================================================================
        private void button_LoggerGetApplicationStatus_Click(object sender, EventArgs e)
        {
            string status_string = "";    // ステータス文字列
            string  error_string;         // エラーコード文字列
            int     ret;                  // 戻り値取得用
            uint    status;               // ステータス格納用

            //----------------------------------------
            // ステータスを取得
            //----------------------------------------
            ret = logger.GetApplicationStatus(g_appid, out status);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetApplicationStatus = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // ステータス取得関数が正常終了した場合
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // ステータスを更新
                //--------------------
                switch (status)
                {
                    case (uint)CLoggerConst.LOGGER_STATUS_STOP:
                        status_string = "停止中";
                        break;
                    case (uint)CLoggerConst.LOGGER_STATUS_START_TRG:
                        status_string = "開始トリガ待ち";
                        break;
                    case (uint)CLoggerConst.LOGGER_STATUS_BUSY:
                        status_string = "動作中";
                        break;
                    default:
                        status_string = "不明な状態";
                        break;
                }
                //----------------------------------------
                // ステータスを表示
                //----------------------------------------
                textBox_ApplicationStatus.Text = string.Format("{0} ({1})", status, status_string);
            }
            return;
        }

        //================================================================================
        // 収集停止ボタンをクリックした際の処理になります
        // アプリの入出力を停止します
        //================================================================================
        unsafe private void button_LoggerStopOperation_Click(object sender, EventArgs e)
        {
            int     ret;                // 戻り値取得用
            string  error_string;       // エラーコード文字列
            uint    sampling_times = 0; // 指定サンプリング回数格納用
            float[] sampling_data;      // サンプリングデータ格納用
            long i;                     // ループカウント用
            string text_string = "";    // テキストボックス更新用
            StreamWriter fp;            // ファイルポインタ
            long j;                     // ループカウント用

            //----------------------------------------
            // イベント通知用デリゲートの固定ポインタを取得
            //----------------------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //----------------------------------------
            // アプリの入出力を停止
            //----------------------------------------
            ret = logger.StopOperation(g_appid);
            if(ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // エラーコード,メッセージを表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerStopOperation = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // サンプリング回数の取得
            //----------------------------------------
            ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // エラーコード,メッセージを表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("GetStoredSamplingCount = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // 指定サンプリング回数分のデータ格納用
            //----------------------------------------
            try
            {
                sampling_data = new float[sampling_times * SequenceNum];
            }
            catch
            {
                textBox_ReturnNum.Text = "デバイス動作終了イベント処理：データ格納用の配列確保に失敗";
                return;
            }
            //----------------------------------------
            // サンプリングデータの取得
            //----------------------------------------
            ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
            if (ret != 0)
            {
                //----------------------------------------
                // エラー文字列取得
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // エラーコード,メッセージを表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                //--------------------
                //データ格納用の配列を解放
                //--------------------
                sampling_data = null;
                return;
            }
            //----------------------------------------
            // ファイルを開く
            //----------------------------------------
            try
            {
                fp = File.AppendText(g_file_name);
            }
            catch
            {
                textBox_ReturnNum.Text = "取得データファイル出力：File.AppendText = file open error.";
                return;
            }
            //--------------------
            // サンプリング回数分ループ
            //--------------------
            for (i = 0; i < sampling_times; i++)
            {
                //--------------------
                // 表示用文字列格納変数をクリア
                //--------------------
                text_string = "";
                //--------------------
                // 表示用文字列の生成
                //--------------------
                text_string += string.Format("{0,5},  ", (g_samplingdata++));
                //--------------------
                // サンプリングデータを追加する（指定したチャネルの数だけ処理を繰り返す）
                //--------------------
                for (j = 0; j < SequenceNum - 1; j++)
                {
                    text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                }
                text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                //--------------------
                // データ書き込み
                //--------------------
                try
                {
                    fp.Write(text_string);
                }
                catch
                {
                    textBox_ReturnNum.Text = "取得データファイル出力：fp.Write = file write error.";
                    fp.Close();
                    //--------------------
                    //データ格納用の配列を解放
                    //--------------------
                    sampling_data = null;
                    return;
                }
            }
            fp.Close();
            //--------------------
            //データ格納用の配列を解放
            //--------------------
            sampling_data = null;

            //----------------------------------------
            // 収集停止完了のメッセージ表示
            //----------------------------------------
            textBox_ReturnNum.Text = "LoggerStopOperation：正常終了";
            return;
        }

        //================================================================================
        // C-LOGGER終了ボタンをクリックした際の処理になります
        // アプリを停止し、アクセスを不可にします
        //================================================================================
        private void button_LoggerCloseApplication_Click(object sender, EventArgs e)
        {
            uint    status          = 0;      // ステータス
            int     ret;                      // 戻り値取得用
            string  error_string;             // エラーコード文字列
            string  status_string;            // ステータス文字列

            //----------------------------------------
            // ファイルを閉じる(先にC-LOGGERが終了することを考慮し、結果を確認しない)
            //----------------------------------------
            logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            //----------------------------------------
            // デアプリ停止し、アクセス不可
            //----------------------------------------
            ret = logger.CloseApplication(g_appid, out status);
            //----------------------------------------
            // エラー文字列取得
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            if (ret != 0)
            {
                //----------------------------------------
                // エラーコード,メッセージを表示
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerCloseApplication = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // ステータス文字列取得
            //----------------------------------------
            switch (status)
            {
                case (uint)CLoggerConst.LOGGER_STATUS_SUCCESS:
                    status_string = "正常終了";
                    break;
                case (uint)CLoggerConst.LOGGER_STATUS_FAILURE:
                    status_string = "C-LOGGER終了エラー";
                    break;
                default:
                    status_string = "不明なエラー";
                    break;
            }
            //----------------------------------------
            // エラーコード,メッセージを表示
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerCloseApplication = {0} : {1} \r\nstatus = {2} : {3}", ret, error_string, status, status_string);
            return;
        }

        //================================================================================
        // 閉じるボタンがクリックされたときの処理です
        // アプリケーションを終了します
        //================================================================================
        private void button_Exit_Click(object sender, EventArgs e)
        {
            uint    status          = 0;      // ステータス

            //----------------------------------------
            // ファイルを閉じる(先にC-LOGGERが終了することを考慮し、結果を確認しない)
            //----------------------------------------
            logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            //----------------------------------------
            // アプリ停止し、アクセス不可
            //----------------------------------------
            logger.CloseApplication(g_appid, out status);
            //----------------------------------------
            // GCHandleの解放
            //----------------------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            //----------------------------------------
            // ダイアログを終了する
            //----------------------------------------
            this.Close();
            return;
        }

        //================================================================================
        // コールバックルーチン
        //================================================================================
        unsafe public int CallBackProc(short Id, uint Event, int wParam, int lParam, void* Param)
        {
            int ret;                    // 戻り値取得用
            uint sampling_times;        // 指定サンプリング回数格納用
            string error_string;        // エラーコード文字列
            float[] sampling_data;      // サンプリングデータ格納用
            long i;                     // ループカウント用
            string text_string = "";    // テキストボックス更新用
            StreamWriter fp;            // ファイルポインタ
            long j;                     // ループカウント用

            //----------------------------------------
            // 指定サンプリング回数格納イベント
            //----------------------------------------
            if (Event == (long)CLoggerConst.LOGGER_PARAM_EVENT_DATANUM)
            {
                //----------------------------------------
                // サンプリング回数の取得
                //----------------------------------------
                ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
                if(ret != 0)
                {
                    //----------------------------------------
                    // エラー文字列取得
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // エラーコード,メッセージを表示
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
                    }));
                    return 0;
                }

                //----------------------------------------
                // 指定サンプリング回数分のデータ格納用
                //----------------------------------------
                try
                {
                    sampling_data = new float[sampling_times * SequenceNum];
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "デバイス動作終了イベント処理：データ格納用の配列確保に失敗";
                    }));
                    return 0;
                }
                //----------------------------------------
                // サンプリングデータの取得
                //----------------------------------------
                ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
                if (ret != 0)
                {
                    //----------------------------------------
                    // エラー文字列取得
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // エラーコード,メッセージを表示
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                    }));
                    //--------------------
                    //データ格納用の配列を解放
                    //--------------------
                    sampling_data = null;
                    return 0;
                }

                //----------------------------------------
                // ファイルを開く
                //----------------------------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "取得データファイル出力：File.AppendText = file open error.";
                    }));
                    return 0;
                }
                //--------------------
                // サンプリング回数分ループ
                //--------------------
                for (i = 0; i < sampling_times; i++)
                {
                    //--------------------
                    // 表示用文字列格納変数をクリア
                    //--------------------
                    text_string = "";
                    //--------------------
                    // 表示用文字列の生成
                    //--------------------
                    text_string += string.Format("{0,5},  ", (g_samplingdata++));
                    //--------------------
                    // サンプリングデータを追加する（指定したチャネルの数だけ処理を繰り返す）
                    //--------------------
                    for (j = 0; j < SequenceNum - 1; j++)
                    {
                        text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                    }
                    text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                    //--------------------
                    // データ書き込み
                    //--------------------
                    try
                    {
                        fp.Write(text_string);
                    }
                    catch
                    {
                        this.Invoke(new Action(() =>
                        {
                            textBox_ReturnNum.Text = "取得データファイル出力：fp.Write = file write error.";
                        }));
                        fp.Close();
                        //--------------------
                        //データ格納用の配列を解放
                        //--------------------
                        sampling_data = null;
                        return 0;
                    }
                }
                fp.Close();
                //--------------------
                //データ格納用の配列を解放
                //--------------------
                sampling_data = null;
            }
            //----------------------------------------
            // デバイス終了イベント
            //----------------------------------------
            else if  (Event == (long)CLoggerConst.LOGGER_PARAM_EVENT_END)
            {
                //----------------------------------------
                // サンプリング回数の取得
                //----------------------------------------
                ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
                if (ret != 0)
                {
                    //----------------------------------------
                    // エラー文字列取得
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // エラーコード,メッセージを表示
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
                    }));
                    return 0;
                }

                //----------------------------------------
                // 指定サンプリング回数分のデータ格納用
                //----------------------------------------
                try
                {
                    sampling_data = new float[sampling_times * SequenceNum];
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "デバイス動作終了イベント処理：データ格納用の配列確保に失敗";
                    }));
                    return 0;
                }
                //----------------------------------------
                // サンプリングデータの取得
                //----------------------------------------
                ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
                if (ret != 0)
                {
                    //----------------------------------------
                    // エラー文字列取得
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // エラーコード,メッセージを表示
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                    }));
                    //--------------------
                    //データ格納用の配列を解放
                    //--------------------
                    sampling_data = null;
                    return 0;
                }

                //----------------------------------------
                // ファイルを開く
                //----------------------------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "取得データファイル出力：File.AppendText = file open error.";
                    }));
                    return 0;
                }
                //--------------------
                // サンプリング回数分ループ
                //--------------------
                for (i = 0; i < sampling_times; i++)
                {
                    //--------------------
                    // 表示用文字列格納変数をクリア
                    //--------------------
                    text_string = "";
                    //--------------------
                    // 表示用文字列の生成
                    //--------------------
                    text_string += string.Format("{0,5},  ", (g_samplingdata++));
                    //--------------------
                    // サンプリングデータを追加する（指定したチャネルの数だけ処理を繰り返す）
                    //--------------------
                    for (j = 0; j < SequenceNum - 1; j++)
                    {
                        text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                    }
                    text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                    //--------------------
                    // データ書き込み
                    //--------------------
                    try
                    {
                        fp.Write(text_string);
                    }
                    catch
                    {
                        this.Invoke(new Action(() =>
                        {
                            textBox_ReturnNum.Text = "取得データファイル出力：fp.Write = file write error.";
                        }));
                        fp.Close();
                        //--------------------
                        //データ格納用の配列を解放
                        //--------------------
                        sampling_data = null;
                        return 0;
                    }
                }
                fp.Close();
                //--------------------
                //データ格納用の配列を解放
                //--------------------
                sampling_data = null;
            }
            return 0;
        }
    }
}
