//---------------------------------------------------------------------------

#include <vcl.h>
#include "ITSSkinF.h"
#include "ITSUtilF.h"
#include "ITSLangTransF.h"
#include "ITSMapF.h"
#pragma hdrstop

#include "FrmMainF.h"
#include "TThreadPollingF.h"
#include "FrmInitializeF.h"  // 프로그램 초기화화면
#include "FrmFacilityAlarmF.h"
#include "FrmIncidentAlarmF.h"

#define D_IDB0140M
#define D_WBH0010Mx
#define D_BLACKBOXx

//---------------------------------------------------------------------------
#include "ITS0000MF.h"  // 통합모니터링
#include "ITS0010MF.h"  // 현재소통정보
#include "ITS0020MF.h"  // 소통정보제보 관리
#include "ITS0030MF.h"  // 돌발상황정보 관리
#include "ITS0040MF.h"  // 반복정체구간관리
//#include "ITS0050MF.h"  // 반복정체구간관리(기상)
//---------------------------------------------------------------------------
#include "IFM0010MF.h"  // 시설물 정보관리
#include "IFM0020MF.h"  // 시설물 업체 관리
#include "IFM0030MF.h"  // 시설물 장애 관리
#include "IFM0040MF.h"  // 시설물장애 이력
#include "IFM0050MF.h"  // 시설물 장애코드 관리
//---------------------------------------------------------------------------
#include "IDB0010MF.h"  // 노드
#include "IDB0020MF.h"  // 링크
#include "IDB0030MF.h"  // 서비스링크
#include "IDB0040MF.h"  // 도로
#include "IDB0050MF.h"  // 가공파라미터관리
#include "IDB0051MF.h"  // 가공파라미터관리
#include "IDB0060MF.h"  // 소통등급관리
#include "IDB0070MF.h"  // 휴일관리
#include "IDB0080MF.h"  // 운영코드 관리
#include "IDB0090MF.h"  // 운영자관리
#include "IDB0100MF.h"  // 서버/프로세스관리
#include "IDB0110MF.h"  // 기관관리
#include "IDB0120MF.h"  // 간선도로관리
#include "IDB0130MF.h"  // 운영자그룹 메뉴관리
#ifdef D_IDB0140M
    #include "IDB0140MF.h"  // 홈페이지 관리자
#endif
//---------------------------------------------------------------------------
#include "IHS0010MF.h"  // 운영자 접속이력
#include "IHS0020MF.h"  // 프로세스상태이력
#include "IHS0030MF.h"  // 수집데이터 이력조회
#include "IHS0040MF.h"  // 가공데이터 이력조회
#include "IHS0060MF.h"  // 수집데이터 이력분석
#include "IHS0070MF.h"  // 교차로 이력분석
//---------------------------------------------------------------------------
#include "IST0010MF.h"  // 인터넷 접속통계
#include "IST0020MF.h"  // CCTV 접속통계
#include "IST0030MF.h"  // 소통정보 통계
#include "IST0040MF.h"  // 돌발상황 통계
#include "IST0050MF.h"  // 시설물 통신단절통계
#include "IST0060MF.h"  // 프로세스 상태통계
#include "IST0070MF.h"  // 도로소통정보 통계
#include "IST0080MF.h"  // 도로소통정보 통계
#include "IRP0010MF.h"  // 보고서
//---------------------------------------------------------------------------
#include "IAN0010MF.h"  // 교통정보 수집결과 분석
#include "IAN0020MF.h"  // 교통정보 가공결과 분석
#include "IAN0030MF.h"  // 교통정보 제공결과 분석
#include "IAN0040MF.h"  // 소통정보 이력분석
#include "IAN0050MF.h"  // 패턴데이터 분석
#include "IAN0060MF.h"  // 반복정체구간 분석
//---------------------------------------------------------------------------
#include "CFG0000MF.h"  // 시스템 환경설정
//---------------------------------------------------------------------------

#ifdef USE_DSRC
    #include "DSRH010MF.h"  //DSRC-RSE 상태이력
    #include "DSRH020MF.h"  //DSRC-RSE 로그이력
    #include "DSRH030MF.h"  //DSRC-RSE 제어이력
    #include "DSRH040MF.h"  //DSRC-RSE 가공정보 이력조회
    #include "DSRH050MF.h"  //DSRC-RSE 제공정보 이력조회
    #include "DSRM010MF.h"  //DSRC-RSE 관리
    #include "DSRM020MF.h"  //DSRC-RSE 제어
    #include "DSRM030MF.h"  //DSRC-RSE 수집구간 설정
    #include "DSRM040MF.h"  //DSRC-RSE 제공구간 관리
    #include "DSRH060MF.h"  //DSRC-RSE OBU 수집 이력조회
    #include "DSRH070MF.h"  //DSRC-RSE OBU 수집 통계조회
#endif
//---------------------------------------------------------------------------
#ifdef USE_VDS
    #include "VDSM000MF.h"  //VDS-검지기 상태 모니터링
    #include "VDSM100MF.h"  //VDS-제어기 관리
    #include "VDSM200MF.h"  //VDS-검지기 관리
    #include "VDSM300MF.h"  //VDS 제어

    #include "VDSH010MF.h"  //VDS-제어기 상태이력
    #include "VDSH020MF.h"  //VDS-제어기 이벤트이력
    #include "VDSH030MF.h"  //VDS-검지기 과거수집이력
    #include "VDSH040MF.h"  //VDS-검지기 원시수집이력
    #include "VDSH050MF.h"  //VDS-검지기 평활화이력
    #include "VDSH060MF.h"  //VDS-검지기 보정이력
    #include "VDSH070MF.h"  //VDS-검지기 상태이력
    #include "VDSH080MF.h"  //VDS-검지기 개별차량 이력

    #include "VDSS010MF.h"  //VDS-검지기 통계조회
    #include "VDSS020MF.h"  //VDS-검지기 통계조회
#endif
//---------------------------------------------------------------------------
#ifdef USE_AVI
    #include "AVIM010MF.h"  //AVI-제어기 관리
    #include "AVIM020MF.h"  //AVI-구간 관리

    #include "AVIH010MF.h"  //AVI-제어기 상태이력
    #include "AVIH020MF.h"  //AVI-제어기 차량인식이력
    #include "AVIH030MF.h"  //AVI-제어기 교통정보이력
    #include "AVIH040MF.h"  //AVI-제어기 차량통과이력
    #include "AVIH050MF.h"  //AVI-구간 매칭이력
    #include "AVIH060MF.h"  //AVI-구간 수집이력
    #include "AVIH070MF.h"  //AVI-구간 소통상황이력
    #include "AVIH080MF.h"  //AVI 지점 원시수집 이력

    #include "AVIS010MF.h"  //AVI-구간 소통상황통계
    #include "AVIS020MF.h"  //AVI-검지기 소통상황통계
#endif
//---------------------------------------------------------------------------
#ifdef USE_PARK
    #include "PIS0010MF.h"  //주차장관리
    #include "PIS0020MF.h"  //주차장실시간정보
    #include "PISH010MF.h"  //주차장실시간정보이력
    #include "PISH020MF.h"  //주차장상태이력
    #include "PIS0030MF.h"  //주차장제어
#endif
//---------------------------------------------------------------------------
#ifdef D_BLACKBOX
    #include "BDS0010MF.h"
    #include "BDS0020MF.h"
    #include "BDSH010MF.h"
    #include "BDSH020MF.h"
#endif
//---------------------------------------------------------------------------
#ifdef USE_WCAM
    #include "WCAM100MF.h"  //웹카메라 관리
    #include "WCAM010MF.h"  //웹카메라 상태모니터링
    //#include "WCAM020MF.h"  //웹카메라 제어
    #include "WCAMH10MF.h"  //웹카메라 상태이력 조회
#endif
//---------------------------------------------------------------------------
#ifdef USE_CCAM
    #include "CCAM100MF.h"  //교차로감시카메라 관리
    #include "CCAM010MF.h"  //교차로감시카메라 상태모니터링
    //#include "CCAM020MF.h"  //교차로감시카메라 제어
    #include "CCAMH10MF.h"  //교차로감시카메라 상태이력 조회
#endif
//---------------------------------------------------------------------------

#include "TAS0010MF.h"
#include "TAS0020MF.h"
#include "TAS0030MF.h"
#include "TAS0040MF.h"
#include "TAS0050MF.h"
#include "TAS0060MF.h"
#include "TAS0070MF.h"
#ifdef USE_VDS
    #include "TAS0080MF.h"
    #include "TAS0090MF.h"
#endif
//---------------------------------------------------------------------------
#ifdef D_WBH0010M
    #include "WBH0010MF.h"      //홈페이지 관리자 이력조회
#endif
//---------------------------------------------------------------------------

#pragma package(smart_init)
#pragma link "cxClasses"
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxHint"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxPC"
#pragma link "cxPCdxBarPopupMenu"
#pragma link "dxBar"
#pragma link "dxCustomHint"
#pragma link "dxRibbon"
#pragma link "dxRibbonGallery"
#pragma link "dxRibbonSkins"
#pragma link "dxRibbonStatusBar"
#pragma link "dxScreenTip"
#pragma link "dxSkinBlack"
#pragma link "dxSkinBlue"
#pragma link "dxSkinChooserGallery"
#pragma link "dxSkinsCore"
#pragma link "dxSkinscxPCPainter"
#pragma link "dxSkinsdxBarPainter"
#pragma link "dxSkinsdxRibbonPainter"
#pragma link "dxSkinsForm"
#pragma link "dxStatusBar"
#pragma link "dxTabbedMDI"
#pragma resource "*.dfm"

TFrmMain *FrmMain = NULL;

#define MAX_EXEPROGRAM  31
ST_RUNPROGRAM  g_RunProgram[MAX_EXEPROGRAM] = {
/* 0*/  {"", "", ""},
/* 1*/  {"TFrmCctvOprMain",     "CctvOprMain.exe",      "CCTV운영관리"},
        {"TFrmCctvCamViewer",   "CctvCamViewer.exe",    "CCTV영상모니터링"},
        {"TfrmCctvLog",         "CctvLog.exe",          "CCTV상태이력"},
        {"", "", ""},

        /* VMS */
/* 5*/  {"TFrmVmsOprMain",      "VmsOprMain.exe",       "VMS운영관리"},
        {"TFrmVmsLogStts",      "VmsLogStts.exe",       "VMS상태이력조회"},
        {"TFrmVmsLogDspl",      "VmsLogDspl.exe",       "VMS제공이력조회"},
        {"TFrmVmsLogCtrl",      "VmsLogCtrl.exe",       "VMS제어이력조회"},
        {"TFrmVmsLogDnld",      "VmsLogDnld.exe",       "VMS다운로드이력조회"},
/*10*/  {"", "", ""},

        /* Web Camera */
/*11*/  {"TFrmWebCamViewer",    "WebCamViewer.exe",     "WEB카메라영상모니터링"},

/*12*/  {"TfrmVdsStatistics",   "VmsMsgLog.exe",        "VDS통계"},
        {"TfrmLinkDSRC",        "DsrcSect.exe",         "DSRC구간설정"},

        //VDS
        {"TfrmVdsMaster",       "VdsMgr.exe",           "VDS 제어기 관리"},
        {"TfrmVdsDetector",     "VdsDetector.exe",      "VDS 검지기 관리"},
        {"TfrmVdsCtrl",         "VdsCtrl.exe",          "VDS 제어"},
        //AVI
        {"TfrmAviMaster",       "AviMgr.exe",           "AVI 제어기 관리"},
        {"TfrmAviDetector",     "AviDetector.exe",      "AVI 검지기 관리"},
        {"TfrmAviLink",         "AviLink.exe",          "AVI 구간 관리"},
        {"TfrmAviControl",      "AviCtrl.exe",          "AVI 제어"},
        //VMS ADD Form
        {"TFrmVmsLogCtl",       "VmsLogCtl.exe",        "VMS제어이력조회"},
        {"TFrmVmsLogDnld",      "VmsLogDnld.exe",       "VMS다운로드이력조회"},

        /* CROSS Camera */
/*23*/  {"TFrmCrsCamViewer",    "CrsCamViewer.exe",     "교차로감시카메라영상모니터링"},

        //ETC
/*24*/  {"TFrmWebCamCtrl",      "WebCamCtrl.exe",       "웹카메라제어"},
        {"", "", ""},
};

#define FORMSHOW(x)     if (x) \
                        { \
                            try { \
                            ShowWindow(x->Handle, SW_RESTORE); \
                            x->BringToFront(); \
                            } catch(...) {} \
                        } \
                        else \
                        { \
                            Application->CreateForm(__classid(T##x), &x); \
                            if (x) x->Show(); \
                        }
//---------------------------------------------------------------------------

class TdxMyBarControl : public TdxBarControl
{
__published:
	__property OnMouseMove;
	__property OnMouseEnter;
	__property OnMouseLeave;
public:
	__fastcall virtual TdxMyBarControl(Classes::TComponent* AOwner) : TdxBarControl(AOwner){};
};
//---------------------------------------------------------------------------
LONG __stdcall HelperExceptionFilter(struct _EXCEPTION_POINTERS * pContext)
{
    LONG  lRet  = EXCEPTION_EXECUTE_HANDLER;
    DWORD dwRet = ERROR_SUCCESS;

	__try
	{
        Application->NormalizeTopMosts();


        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"시스템에서 알수없는 오류가 발생했습니다.\r\n프로그램을 다시 기동해 주세요.",
                                    L"시스템 오류", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"The system encountered an unknown error.\r\nPlease re-start the program.",
                                    L"System error", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }

        Application->RestoreTopMosts();
        //TerminateProcess(GetCurrentProcess(), 0);
	}
	__finally
	{
		if(ERROR_SUCCESS != dwRet)
		{
			lRet = EXCEPTION_CONTINUE_SEARCH;
		}
		exit(0);
	}
	return lRet;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnMenuMouseMove(TObject *Sender, TShiftState Shift, int X, int Y)
{
    ::SetCursor(Screen->Cursors[crHandPoint]);
}
//---------------------------------------------------------------------------
__fastcall TFrmMain::TFrmMain(TComponent* Owner)
    : TdxCustomRibbonForm(Owner)//TdxCustomRibbonForm(Owner)//TForm(Owner)
{
    //::CoInitialize(NULL);
    Caption = g_AppCfg.sTitle;

    Application->OnException = OnAppException;
    LangTrans->Translate(this, ITSDb_GetConnection());
    ITSSkin_Initialize(Application, g_AppCfg.sLang, true, true);

	TmrOnShow->Enabled = false;
    TmrAppState->Enabled = false;
    FLogoutTick = 0;

    g_AppCfg.lMainWinHandle = (long)Handle;
    StartJobThread();
    while(!PostJobMessage(WM_THREAD, WP_PING)) ;

    String sCaption = "";
    ReadConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "CAPTION", sCaption);
    ITSSkin_Caption(sCaption == "1" ? true : false);

    //탭메뉴비활성
    //TabTrafficAnalysisSupport->Visible = false;
    BarTrafficAnalysisSupport1->Visible = false;
    BarTrafficAnalysisSupport2->Visible = false;
    NTAS0010M->Visible   = ivNever; //혼잡지도 분석
    NTAS0040M->Visible   = ivNever; //교통분석지원 - 특수일 분석
    NTAS0030M->Visible   = ivNever; //간선도로 속도분석

#ifndef USE_VDS
    BarVdsAnalysis->Visible = false;
#endif

    TabBlackBox->Visible = false;   //BlackBox
    TabAvi->Visible      = false;
    TabDsrc->Visible     = false;
    TabSms->Visible      = false;   //SMD

    //주차장
#ifdef USE_PARK
    TabParking->Visible  = true;
#else
    TabParking->Visible  = false;
#endif

    NCCTV100M->Visible = ivNever;   //CCTV 관리
    RCCTVH10M->Visible = ivNever;   //CCTV 상태이력
    NCCTV010M->Visible = ivNever;   //CCTV 상태 모니터링
    NCCTVR10R->Visible = ivNever;   //CCTV 영상 모니터링
    NCCTV020M->Visible = ivNever;   //CCTV 제어

    NIDB0110M->Visible = ivNever;   //연계기관 관리

    BarConfig4->Visible = false;    //스킨
    BarCrsCam4->Visible = false;
    NWCAM010M->Visible  = ivNever;

    // 메뉴비활성
#ifndef D_IDB0140M
    NIDB0140M->Visible = ivNever;
#endif
#ifndef D_WBH0010M
    NWBH0010M->Visible = ivNever;
#endif

    //환경설정
    NCFG0001M->Visible = ivNever;   //지도 레이어설정
    //통계-분석
    NIST0010M->Visible = ivNever;   //인터넷접속 통계
    NIST0020M->Visible = ivNever;   //CCTV접속 통계
    //NIAN0040M->Visible = ivNever;   //소통정보이력 분석 - 남양주(교통정보분석지원 메뉴에서 대체)
    //시설물관리
    NIFM0040M->Visible = ivNever;   //시설물장애 이력
    NIFM0050M->Visible = ivNever;   //시설물 장애코드 관리
    //AVI
    RAVIC010M->Visible = ivNever;   //AVI 제어[R]
    //VMS
    //RVMSH300M->Visible = ivNever;   //VMS 제어이력(R)
    RVMSH400M->Visible = ivNever;   //VMS 다운로드이력(R)
    //주차장
    //NPIS0030M->Visible = ivNever;   //주차장 제어
    NITS0050M->Visible = ivNever;   //반복정체관리(기상)

    //NIAN0060M->Visible = ivNever;   //반복정체구간 분석 ==> 실제 반복정체구간 분석이 아님(????)

    //Ribon config
    Ribbon->ShowTabGroups = true;   // 메뉴탭 show/hide
    Ribbon->QuickAccessToolbar->Visible = false;
    //Ribbon->ApplicationButton->Visible = false;
    Ribbon->SupportNonClientDrawing = true;
    Ribbon->EnableTabAero = true;

    //Active Tab set
    TabTraffic->Active = true;

    SetColorScheme(g_AppCfg.sSkinName);

    CMM_SetFormPosition(g_AppCfg.bSaveForm);
    CMM_LoadForm(g_sFormsDir, this);

#if 1
    int nCompnentCnt = this->ComponentCount;
    for (int ii = 0; ii < nCompnentCnt; ii++)
    {
        String sClassName = this->Components[ii]->ClassName();
        if(sClassName == "TdxBar")
        {
            TdxBar *pMenuGrp = (TdxBar *)this->Components[ii];
            if (pMenuGrp->Visible == false) continue;
            static_cast<TdxMyBarControl *>(pMenuGrp->Control)->OnMouseMove = OnMenuMouseMove;
        }
    }
#endif

    APP_InitDisplayColor();
	//ITSSkin_Menu(this);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::FormCreate(TObject *Sender)
{
    /* 레지스터리 등록 IE 최신버전 */
    String sExeName = ExtractFileName(Application->ExeName);
    ITSMap_Init(sExeName);
    //SetUnhandledExceptionFilter(HelperExceptionFilter);

    Application->ShowMainForm = false;
     
    try {
        Application->Icon->LoadFromResourceName(((unsigned int)HInstance), "MAINICON");
    } catch(...) { ShowMessage("LoadFromResourceName failed"); }

    //DeleteLogFiles((PTCHAR)g_sLogDir.c_str(), 30, (PTCHAR)"*.*");


    WindowState = wsMaximized;

    // 종료조건이 있는경우..
    //Application->Terminate();
    //return;

    Application->ShowMainForm = true;
    Application->OnHint       = OnAppHint;

    ImgAlarm->Visible = false;
    ImgAlarmNormal->Visible = true;
}
//---------------------------------------------------------------------------
void __fastcall TFrmMain::FormShow(TObject *Sender)
{
    Application->ProcessMessages();
    g_AppCfg.lMainWinHandle = (long)Handle;

    /*
    *  프로그램 초기화 작업
    */
    InitStatusBar();

	if (g_pLOGIN)
    {
        GetUserMenuRight(g_pLOGIN->sUserId, g_pLOGIN->sUserRightId);
    }

	TmrOnShow->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TmrOnShowTimer(TObject *Sender)
{
	TmrOnShow->Enabled = false;
	Application->ProcessMessages();

    TFrmInitialize *FrmInitialize = new TFrmInitialize(this);
    FrmInitialize->FThreadId = g_AppCfg.thr.dwThreadId;
    FrmInitialize->ShowModal();

    //폴링작업 객체 초기화
    FPollTraffic00.Cycle  = (60*1000*2)+ 5; // 링크소통정보(전체)
    FPollTraffic05.Cycle  = (60*1000*5)+ 0; // UTIS운영정보
    FPollDatabase.Cycle   = (60*1000*5)+ 3; // 데이터베이스상태정보

    FPollStatus01.Cycle   = (60*1000*1)+ 1; // 시설물상태정보
    FPollStatus02.Cycle   = (60*1000*5)+ 3; // 프로세스상태정보
    FPollStatus03.Cycle   = (60*1000*1)+ 5; // 돌발정보

    FPollEvent01.Cycle    = (60*1000*1)+ 1;  // 블랙박스이벤트
    FPollVilgFrcs.Cycle   = (120*1000*10)+1;  // 기상정보

    FPollTraffic00.IsPolling = true; // 링크소통정보(전체)
#ifdef USE_UTIS
    FPollTraffic05.IsPolling = true; // UTIS운영정보
#else
    FPollTraffic05.IsPolling = false; // UTIS운영정보
#endif

    FPollDatabase.IsPolling  = true; // 데이터베이스상태정보
    FPollStatus01.IsPolling  = true; // 시설물상태정보
    FPollStatus02.IsPolling  = true; // 프로세스상태정보
    FPollStatus03.IsPolling  = true; // 돌발정보

    FPollEvent01.IsPolling  = false; // 블랙박스이벤트
    FPollVilgFrcs.IsPolling = true;  // 기상정보

    //내부통신 초기화 시작...
    TItsProcess *pPrcs = ItsProcessManager->FLists.Find(g_AppCfg.sProcessId);
    if (!pPrcs)
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_1", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }

    int nPort = pPrcs->PRGM_PORT.ToIntDef(4602);
    int nResult = CComm_Initialize((long)Handle, g_AppCfg.sProcessId, "UOT", nPort, g_AppCfg.sLogDay);
    if (VERR_NONE != nResult)
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_2", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_2", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }
    FOR_STL(TItsProcess*, pObj, ItsProcessManager->FLists)
    {
        if (pObj->DEL_YN == "Y") continue;
        AnsiString sProcessId = AnsiString(pObj->SYST_ID);
        AnsiString sSystemTp  = AnsiString(pObj->SYST_TYPE);
        AnsiString sIpAddress = AnsiString(pObj->SYST_IP_1);
        AnsiString sUdpPort   = AnsiString(pObj->PRGM_PORT);
        if (CComm_AddProcess(sProcessId, sSystemTp, sIpAddress, sUdpPort) >= 0)
        {
#if 0
            if ("UOT" == sSystemTp)
            {
                nPort = sUdpPort.ToIntDef(0);
                CComm_AddProcess(sProcessId, sSystemTp, sIpAddress, AnsiString(nPort+1));
            }
#endif
        }
    }
    if (VERR_NONE != CComm_Open())
    {
        if (g_AppCfg.sLang == "kr")
        {
            Application->MessageBox(L"통신프로세스를 초기화 하지 못하였습니다.\r\n환경설정에서 시스템ID를 확인하세요.\r\n프로그램을 종료합니다.",
                                    L"프로그램 통신오류_3", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        else
        {
            Application->MessageBox(L"Failed to initialize communication process.\r\nPlease check your system ID in preferences.\r\nExit the program.",
                                    L"Program communication error_3", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        }
        g_AppCfg.bAppClose = true;
        Close();
        return;
    }
    //내부통신 초기화 끝...

    ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbComm]->PanelStyle)->ImageIndex = 8;

	Application->ProcessMessages();

    ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = ITSDb_IsOpen() ? 8 : 7;

    //TODO NITS0000MClick((TObject *)NITS0000M);    //메인화면을 프로그램 기동과 동시에 호출하는 경우

#if 0
    if (g_AppCfg.AutoLogout.LogoutExit)
    {
        Application->MessageBox(L"이전 프로그램은 자동로그아웃으로 종료되었습니다.\r\n프로그램을 실행합니다.",
                                L"프로그램 실행정보", MB_OK|MB_ICONQUESTION|MB_APPLMODAL);
    }
#endif
    g_AppCfg.AutoLogout.LogoutExit = false;

    TmrAppState->Enabled = true;
    TmrPolling->Enabled = true;
    TmrDbCheck->Enabled = true;
}
//---------------------------------------------------------------------------

bool  __fastcall TFrmMain::StartJobThread()
{
    TThreadPolling *pPollingThread = new TThreadPolling(false);
    if (pPollingThread)
    {
        pPollingThread->OnTerminate = OnPollingThreadDone;
        g_AppCfg.thr.pThread    = (TThread *)pPollingThread;
        g_AppCfg.thr.dwThreadId = pPollingThread->ThreadID;
        g_AppCfg.thr.nHandle    = pPollingThread->Handle;
        //pPollingThread->Resume();
        return true;
    }
    return false;
}
//---------------------------------------------------------------------------

void  __fastcall TFrmMain::TerminateJobThread()
{
    if (g_AppCfg.thr.bRunning)
    {
        PostJobMessage(WM_THREAD, WM_QUIT);
    }
    
    Sleep(500);
    try
    {
        if (g_AppCfg.thr.bRunning)
        {
            TThreadPolling *pThread = (TThreadPolling *)g_AppCfg.thr.pThread;
            pThread->Terminate();
            //pThread->WaitFor();
        }
        g_AppCfg.thr.pThread    = NULL;
        g_AppCfg.thr.dwThreadId = 0;
        g_AppCfg.thr.nHandle    = 0;
        g_AppCfg.thr.bRunning   = false;
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    // 폼이 닫히기 전에 수행해야 할 모뮬 기술
    // 프로그램 종료를 사용자가 확인할 수 있도록...
	if (!g_AppCfg.bAppClose)
    {
        String strMsg;
        strMsg = "";
        strMsg = "[ " + g_AppCfg.sTitle + " ]\r\n\n";
        strMsg+= FrmLang->cxLabel1->Caption;

		if(Application->MessageBox(strMsg.c_str(),
                                   FrmLang->cxLabel2->Caption.c_str(),
                                   MB_YESNO|MB_ICONQUESTION) == IDYES)
        {
            /*
            *  화면관련 작업을 못하도록 여기에 코드를 적자...
            */
            CloseAllWindow();

            ITSDb_ApplicationTerm();
			g_AppCfg.bAppClose = true;
        }
        CanClose = false;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::FormClose(TObject *Sender, TCloseAction &Action)
{
    CommClose();
    Action = caFree;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::CommClose()
{
    try
    {
        CComm_Close();

        //CloseAllWindow();

        ITSSkin_Term();

        CMM_SaveForm(g_sFormsDir, this);

        WriteConfigInfo(g_AppCfg.sConfigFile, "MAP", "MAPTYPE", String(g_GisInfo.mapType));
        WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "LOGDAY", Now().FormatString("dd"));

        ::CoUninitialize();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::CloseAllWindow()
{
    int ii;

    // 실행시킨 프로그램을 종료시킨다.
#if 0
    for (ii = 0; ii < MAX_EXEPROGRAM; ii++)
    {
        if (g_RunProgram[ii].AClassName == "")
            continue;

        TermItsProgram(g_RunProgram[ii].AClassName, "");
    }
#endif

    //실행중인 화면을 종료 시킨다.
    try {
        int nForms = Screen->FormCount;
        for (ii = nForms-1; ii >= 0; ii--)
        {
            if (Screen->Forms[ii] != this)
            {
                if (::IsWindow(Screen->Forms[ii]->Handle))
                {
                    String sFormName = Screen->Forms[ii]->Name; 
                    if (sFormName.Pos("ITSSkin")) continue;
                    if (sFormName.Pos("FrmSkin")) continue;
                    if (sFormName.Pos("FrmLang")) continue;
                    if (sFormName.Pos("PlugInChart")) continue;
                    //if (sFormName.SubString(1, 11) == "PlugInChart") continue;

                    if (Screen->Forms[ii]->Owner == this ||
                        Screen->Forms[ii]->Owner == Application)
                    {
                        //Screen->Forms[ii]->Close();
                        PostMessage(Screen->Forms[ii]->Handle, WM_CLOSE, 0, 0);
                        //Application->ProcessMessages();
                        try {
                        WaitForSingleObject(Screen->Forms[ii]->Handle, 1000);
                        }catch(Exception &e) {}
                    }
                }
                Application->ProcessMessages();
            }
        }
    } catch(...) {}
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TmrAppStateTimer(TObject *Sender)
{
    /*
    *  타이머가 1초간격으로 응용프로그램의 상태를 체크하고
    * 응용프로그램의 상태를 주기적으로 체크하여 필요한 조치를 수행한다.
    */
	if (g_AppCfg.bAppClose)
    {
        TmrAppState->Enabled = false;
        TmrPolling->Enabled = false;
        TmrDbCheck->Enabled = false;

        UserLogout(); // 로그아웃

        TerminateJobThread();

        ITSDb_Close();
        Close();                // 응용프로그램 종료
    }
    else
    {
        TmrAppState->Enabled = false;
        UpdateStatusBar();
        //UpdateCommStatus();

        if (g_AppCfg.AutoLogout.Enabled)
        {
            FLogoutTick++;
            if (FLogoutTick > (g_AppCfg.AutoLogout.IntervalMin*60))
            {
                //자동로그아웃처리
                g_AppCfg.bAppClose = true;
                g_AppCfg.AutoLogout.LogoutExit = true;
            }
        }
        TmrAppState->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::UpdateCommStatus()
{
static bool bStatus = false;
#if 0
    if (CenterThreadMonitoring(true))
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbComm]->PanelStyle)->ImageIndex = 7;
    }
    else
#endif
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbComm]->PanelStyle)->ImageIndex = bStatus ? 8 : 7;
        bStatus = !bStatus;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::UpdateStatusBar()
{
    try
    {
        dxStatusBar->Panels->Items[isbTime]->Text = Now().FormatString(STR_DATETIME);
#if 0
        if (ITSDb_IsOpen())
        {
            if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex != 8)
                ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = 8;
        }
        else 
        {
            if (((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex != 7)
                ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex = 7;
        }
#endif
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::DebugMsg(String AMsg)
{
    dxStatusBar->Panels->Items[isbMsg]->Text = " " + AMsg;
    dxStatusBar->Panels->Items[isbMsg]->StatusBarControl->Refresh();    
    TmrDebugHide->Enabled = false;
    TmrDebugHide->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TmrDebugHideTimer(TObject *Sender)
{
    dxStatusBar->Panels->Items[isbMsg]->Text = "";
    dxStatusBar->Panels->Items[isbMsg]->StatusBarControl->Refresh();    
    TmrDebugHide->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::InitStatusBar()
{
    try
    {
        dxStatusBar->Panels->Items[isbGisPos]->Text = "";
        dxStatusBar->Panels->Items[isbTime]->Text = Now().FormatString(STR_DATETIME);

        if (g_pLOGIN)
        {
            String sUserName = g_pLOGIN->sUserName.Trim();
            if (sUserName == "") sUserName = g_pLOGIN->sUserId;
            dxStatusBar->Panels->Items[isbUser]->Text = sUserName;
            ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbUser]->PanelStyle)->ImageIndex = 9;
        }
        else
        {
            //dxStatusBar->Panels->Items[isbUser]->Text = g_pLOGIN->sUserName;// = "로그인 X";
            ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbUser]->PanelStyle)->ImageIndex = 9;
        }

        //dxStatusBar->Panels->Items[isbScale]->Visible = false;
        //dxStatusBar->Panels->Items[isbPos]->Visible = false;
        dxStatusBar->Panels->Items[isbHint]->Text = "";
        dxStatusBar->Panels->Items[isbMsg]->Text = "";
        //dxStatusBar->Panels->Items[isbDb]->Text = "DB";
        //dxStatusBar->Panels->Items[isbComm]->Text = "통신";
        
        UpdateStatusBar(); 
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

bool __fastcall TFrmMain::GetUserMenuRight(String AUserId, String AUserRight)
{
    String sQry;
    TADOQuery *pADO = NULL;
    try
    {
        sQry = "SELECT OPERSYST_MENU_ID                  \r\n"
               "  FROM TB_USER_GROP_MENU_ATHR            \r\n"
               " WHERE ATHR_YN = 'N'                     \r\n"
               "   AND GROP_ID = (SELECT GROP_ID         \r\n"
               "                    FROM TB_USER_INFR    \r\n"
               "                   WHERE USER_ID = :p01) \r\n";

        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

            ITSDb_SQLText(pADO, sQry);
            ITSDb_SQLBind(pADO, "p01", AUserId);
            ITSDb_SQLOpen(pADO);

            for( ; !pADO->Eof; pADO->Next())
            {
                String sMenuId = pADO->FieldByName("OPERSYST_MENU_ID")->AsString;

                try
                {
                    int nCompnentCnt = this->ComponentCount;
                    for (int ii = 0; ii < nCompnentCnt; ii++)
                    {
                        String sClassName = this->Components[ii]->ClassName();
                        if(sClassName == "TdxBarLargeButton")
                        {
                            TdxBarLargeButton *pMenu = (TdxBarLargeButton *)this->Components[ii];
                            if (pMenu->Name == sMenuId)
                            {
                                pMenu->Enabled = false;
                                break;
                            }
                        }
                    }
                }
                catch(...)
                {
                }
            }
        }
        catch(EDatabaseError &E)
        {
            DBERRORLOG("TFrmMain::GetUserMenuRight", String(E.ClassName()), E.Message, sQry);
            throw Exception(String(E.ClassName()) + E.Message);
        }
        catch(Exception &e)
        {
            DBERRORLOG("TFrmMain::GetUserMenuRight", String(e.ClassName()), e.Message, sQry);
            throw Exception(String(e.ClassName()) + e.Message);
        }
	}
	__finally
	{
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
	}
    return true;
}
//---------------------------------------------------------------------------

HWND __fastcall TFrmMain::FindChildWindow(String sFormName)
{
    int nFormCnt = Screen->FormCount;
    for (int ii = 0; ii < nFormCnt; ii++)
    {
        TForm *pForm = Screen->Forms[ii];
        String sTmpFormName = pForm->Name.SubString(1, sFormName.Length());
        if (sTmpFormName == sFormName)
        {
            return pForm->Handle;
        }
    }

    return NULL;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnSkinClick(TObject *Sender)
{
    TdxBarButton *pMenu = (TdxBarButton*)Sender;
    try {
        dxSkinController1->SkinName = pMenu->Caption;
        dxSkinController1->Refresh();
        //ITSSkin_SetName(dxSkinController1->SkinName);   
    } catch(...) {}
    
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TmrPollingTimer(TObject *Sender)
{
    TmrPolling->Enabled = false;

    DWORD dwTick = GetTickCount();

    UpdateThreadStatus(true);   //작업스레드 실행 확인

    // 링크소통정보(전체)
    if (FPollTraffic00.IsPolling && FPollTraffic00.IsPollingTime(dwTick))
    {
        SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
        FPollTraffic00.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_TRAFFIC);
        DebugMsg(FrmLang->cxLabel3->Caption + FrmLang->cxLabelReq->Caption);
    }

    // 데이터베이스 상태
    if (FPollDatabase.IsPolling && FPollDatabase.IsPollingTime(dwTick))
    {
        FPollDatabase.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_DATABASE_STTS);
        DebugMsg(FrmLang->cxLabel25->Caption + FrmLang->cxLabelReq->Caption);
    }

    // 시설물상태정보
    if (FPollStatus01.IsPolling && FPollStatus01.IsPollingTime(dwTick))
    {
        FPollStatus01.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_FACILITY_STTS);
        DebugMsg(FrmLang->cxLabel8->Caption + FrmLang->cxLabelReq->Caption);
    }

    // 프로세스상태정보
    if (FPollStatus02.IsPolling && FPollStatus02.IsPollingTime(dwTick))
    {
        FPollStatus02.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_PROCESS_STTS);
        DebugMsg(FrmLang->cxLabel9->Caption + FrmLang->cxLabelReq->Caption);
    }

    // 돌발정보
    if (FPollStatus03.IsPolling && FPollStatus03.IsPollingTime(dwTick))
    {
        FPollStatus03.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_INCIDENT);
        DebugMsg(FrmLang->cxLabel10->Caption + FrmLang->cxLabelReq->Caption);
    }

    // UTIS운영정보
    if (FPollTraffic05.IsPolling && FPollTraffic05.IsPollingTime(dwTick))
    {
        FPollTraffic05.Polling = dwTick;
        DebugMsg(FrmLang->cxLabel18->Caption + FrmLang->cxLabelReq->Caption);   //UTIS운영정보 조회, Database 운영정보조회
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_05);
    }

    // 블랙박스이벤트
    if (FPollEvent01.IsPolling && FPollEvent01.IsPollingTime(dwTick))
    {
        FPollEvent01.Polling = dwTick;
        //PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_16);
        DebugMsg(FrmLang->cxLabel11->Caption + FrmLang->cxLabelReq->Caption);
    }

    if (FPollVilgFrcs.IsPolling && FPollVilgFrcs.IsPollingTime(dwTick))
    {
        FPollVilgFrcs.Polling = dwTick;
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_WEATHER);
        DebugMsg(FrmLang->cxLabel12->Caption + FrmLang->cxLabelReq->Caption);
    }

    if (Now().FormatString("nn") == "13")
    {
        // 매시 10분에 기상정보를 저장하니까 13분에 디비에서 읽자
        String sCurrTm = Now().FormatString("hh");
    }

    if (!g_AppCfg.bAppClose) TmrPolling->Enabled = true;
}
//---------------------------------------------------------------------------

bool  __fastcall TFrmMain::PostJobMessage(UINT nMsg, int WParam/*=0*/, int LParam/*=0*/)
{
    int nRes;

    String sMsg;
    sMsg.printf(L"PostJobMessage: Msg: %02X, WParam: %02X, LParam: %02X", nMsg, WParam, LParam);
    DebugMsg(sMsg);

    if (g_AppCfg.thr.dwThreadId)
    {
        for (int ii = 0; ii < 3; ii++)
        {
            if (PostThreadMessageW(g_AppCfg.thr.dwThreadId, nMsg, WParam, LParam))
            {
                nRes = 0;
                return true;
            }
            else
            {
                nRes = GetLastError();
                if (ERROR_INVALID_THREAD_ID == nRes) 
                {
                    Sleep(500);
                    continue;
                }
            }
        }
    }
    return false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0000MClick(TObject *Sender)
{
    FORMSHOW(ITS0000M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0010MClick(TObject *Sender)
{
    FORMSHOW(ITS0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0020MClick(TObject *Sender)
{
    FORMSHOW(ITS0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0030MClick(TObject *Sender)
{
    FORMSHOW(ITS0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0040MClick(TObject *Sender)
{
    FORMSHOW(ITS0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0010MClick(TObject *Sender)
{
    FORMSHOW(IDB0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0020MClick(TObject *Sender)
{
    FORMSHOW(IDB0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0030MClick(TObject *Sender)
{
    FORMSHOW(IDB0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0040MClick(TObject *Sender)
{
    FORMSHOW(IDB0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0120MClick(TObject *Sender)
{
    FORMSHOW(IDB0120M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0130MClick(TObject *Sender)
{
    FORMSHOW(IDB0130M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0050MClick(TObject *Sender)
{
    FORMSHOW(IDB0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0060MClick(TObject *Sender)
{
    FORMSHOW(IDB0060M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0070MClick(TObject *Sender)
{
    FORMSHOW(IDB0070M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0080MClick(TObject *Sender)
{
    FORMSHOW(IDB0080M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0090MClick(TObject *Sender)
{
    FORMSHOW(IDB0090M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0110MClick(TObject *Sender)
{
    FORMSHOW(IDB0110M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0100MClick(TObject *Sender)
{
    FORMSHOW(IDB0100M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NCFG0000MClick(TObject *Sender)
{
    String sIniFile = ChangeFileExt(ExtractFileName(Application->ExeName), ".ini");
    CFG0000M = new TCFG0000M(this);
    CFG0000M->IniFile = sIniFile;
    CFG0000M->ShowModal();
    delete CFG0000M;
    CFG0000M = NULL;

    if (NITS0000M->Enabled)
    {
        HWND hWnd = FindChildWindow("ITS0000M");
        if (hWnd) POST_MSG(hWnd, WM_MAINFORM, WP_DB_SELECT_OK, LP_MSG_FACILITY_STTS);
    }

    ShowFacilityStatus();
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NCFG0001MClick(TObject *Sender)
{
#if 0
    try {
        if (ITS00MAP)
        {
            ITS00MAP->ShowLayerEditForm();
        }
        else
        {
            Application->MessageBox(L"지도레이어 설정은 메인화면이 실행되어 있을때 설정할 수 있습니다.\r\n메인화면을 먼저 실행하세요.",
                                    L"지도레이어 설정", MB_OK|MB_ICONWARNING|MB_APPLMODAL);
        }
    } catch(...) {}
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::dxSkinChooserGalleryItem1SkinChanged(TObject *Sender, const UnicodeString ASkinName)
{
    g_AppCfg.sSkinName = ASkinName;

    WriteConfigInfo(g_AppCfg.sConfigFile, "APPLICATION", "SKINNAME", g_AppCfg.sSkinName);

    SetColorScheme(ASkinName);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::SetColorScheme(String ASkinName)
{
    Ribbon->ColorSchemeName = ASkinName;

    dxSkinController1->SkinName = ASkinName;
    dxSkinController1->Refresh();

    dxTabbedMDIManager1->LookAndFeel->SkinName = ASkinName;
    dxStatusBar->Invalidate();
    //Panel1->Color = Ribbon->ColorScheme->GetPartColor(rfspRibbonForm);

    //Ribbon.ColorSchemeName := AName;
    //SkinChooserSelectSkinName(AName);
    //Panel1.Color := Ribbon.ColorScheme.GetPartColor(rfspRibbonForm);
    //dxStatusBar.Invalidate;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::ExecuteItsProgram(String AClassName, String AExeName, String AOption)
{
	HWND hExeForm = FindWindow(AClassName.c_str(), NULL);
	if (hExeForm)
	{
		SetWindowPos(hExeForm, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
	}
	else
	{
        String sExeName = "";
        String sExeParam= "";
        //if (!ReadConfigInfo(g_AppCfg.sConfigFile, "PROGRAM", AOption, sExeName))
        {
            if (g_AppCfg.sAppPath == "")
            {
                sExeName = AExeName;
            }
            else
            {
                sExeName = g_AppCfg.sAppPath + "\\" + AExeName;
            }
            sExeParam = g_pLOGIN->sUserId;
        }
		ShellExecute(Handle, NULL, sExeName.c_str(), sExeParam.c_str(), NULL, SW_SHOWNORMAL);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TermItsProgram(String AClassName, String AExeName)
{
	HWND hExeForm = FindWindow(AClassName.c_str(), NULL);
	if (hExeForm)
	{
        POST_MSG(hExeForm, WM_CLOSE, 0, 0);
	}
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIFM0010MClick(TObject *Sender)
{
    FORMSHOW(IFM0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIFM0020MClick(TObject *Sender)
{
    FORMSHOW(IFM0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIFM0030MClick(TObject *Sender)
{
    FORMSHOW(IFM0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnRunProgramClick(TObject *Sender)
{
    TdxBarLargeButton *pButton = (TdxBarLargeButton*)Sender;
    int nIdx = pButton->Tag;

    if (nIdx < 0 || nIdx >= MAX_EXEPROGRAM)  return;
    if (g_RunProgram[nIdx].AClassName == "") return;

    ExecuteItsProgram(g_RunProgram[nIdx].AClassName, g_RunProgram[nIdx].AExeName, g_RunProgram[nIdx].AOption);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0010MClick(TObject *Sender)
{
    FORMSHOW(IHS0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0020MClick(TObject *Sender)
{
    FORMSHOW(IHS0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0030MClick(TObject *Sender)
{
    FORMSHOW(IHS0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0040MClick(TObject *Sender)
{
    FORMSHOW(IHS0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0010MClick(TObject *Sender)
{
    FORMSHOW(IAN0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0020MClick(TObject *Sender)
{
    FORMSHOW(IAN0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0030MClick(TObject *Sender)
{
    FORMSHOW(IAN0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0040MClick(TObject *Sender)
{
    FORMSHOW(IAN0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0050MClick(TObject *Sender)
{
    FORMSHOW(IAN0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIAN0060MClick(TObject *Sender)
{
    FORMSHOW(IAN0060M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0010MClick(TObject *Sender)
{
    FORMSHOW(IST0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0020MClick(TObject *Sender)
{
    FORMSHOW(IST0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0030MClick(TObject *Sender)
{
    FORMSHOW(IST0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0070MClick(TObject *Sender)
{
    FORMSHOW(IST0070M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0080MClick(TObject *Sender)
{
    FORMSHOW(IST0080M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0040MClick(TObject *Sender)
{
    FORMSHOW(IST0040M);
}
//---------------------------------------------------------------------------

/*
 * 시설물 통신단절통계화면 호출
 */
void __fastcall TFrmMain::NIST0050MClick(TObject *Sender)
{
    FORMSHOW(IST0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIST0060MClick(TObject *Sender)
{
    FORMSHOW(IST0060M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIRP0010MClick(TObject *Sender)
{
    FORMSHOW(IRP0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnAppHint(TObject *Sender)
{
    dxStatusBar->Panels->Items[isbHint]->Text = " " + Application->Hint;
    dxStatusBar->Panels->Items[isbHint]->StatusBarControl->Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnAppException(TObject *Sender, Exception *exception)
{
	if (g_AppCfg.bAppClose)
    {
        ITSDb_Close();
        Close();                // 응용프로그램 종료
    }

    String sClassName = (NULL != Sender)        ? Sender->ClassName() : String("Unknown_Class");
    String sErrMsg    = (NULL != exception)     ? exception->Message  : String("Unknown_Error");
    String sError     = sClassName + " : " + sErrMsg;

    //Application->ShowException(&exception);

    if (sError.Pos("ORA") || sError.Pos("TBR"))
    {
        ITSDb_Close();
    }
    else
    {
        Application->NormalizeTopMosts();
        Application->MessageBox(sError.c_str(), L"System Error", MB_OK|MB_ICONERROR|MB_APPLMODAL);
        Application->RestoreTopMosts();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::UpdateThreadStatus(bool ARequest, bool APing/*=true*/)
{
return;
    try
    {
        if (APing) if (ARequest) PostJobMessage(WM_THREAD, WP_PING);
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbStatus]->PanelStyle)->ImageIndex =  ARequest ? 7 : 8;
        dxStatusBar->Panels->Items[isbDb]->StatusBarControl->Refresh();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::UpdateDbStatus(bool ASelect)
{
    try
    {
        ((TdxStatusBarTextPanelStyle*)dxStatusBar->Panels->Items[isbDb]->PanelStyle)->ImageIndex =  ASelect ? 7 : 8;
        dxStatusBar->Panels->Items[isbDb]->StatusBarControl->Refresh();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::ApplicationEvents1Message(tagMSG &Msg, bool &Handled)
{
    switch(Msg.message)
    {
    case WM_THREAD:
        switch(Msg.wParam)
        {
        case WP_PING:
            UpdateThreadStatus(false);  //스레드 핑 확인
            break;
        case WP_PARAM_TRAFFIC:
            break;
        case WP_DB_SELECT_START:
            UpdateDbStatus(true);
            break;
        case WP_DB_SELECT_OK:
        case WP_DB_SELECT_ERROR:
        case WP_DB_SELECT_CANCEL:
            UpdateDbStatus(false);
            if (Msg.wParam == WP_DB_SELECT_OK)
            {
                OnRefreshMessage(Msg.wParam, Msg.lParam);
            }
            else
            {
                DebugMsg(FrmLang->cxLabel13->Caption);
            }
            break;
        }
        break;
    case WM_DATABASE_REFRESH:
        OnDatabaseMessage(Msg.wParam, Msg.lParam);
        break;
    case WM_PLUGINFORM:
        OnRefreshMessage(Msg.wParam, Msg.lParam);
        break;
    case WM_MOUSEMOVE:
        FLogoutTick = 0;
        break;
    case WM_KEYDOWN:
        FLogoutTick = 0;
        if (Msg.wParam == VK_F5)
        {
            Handled = true;
        }
        break;
    case WM_KEYUP:
        FLogoutTick = 0;
        break;
    case WM_USER+0xF4:
        if (Msg.wParam == 0xB2)
        {
            ITSDb_Close();
            DebugMsg(FrmLang->cxLabel14->Caption);
        }
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::ApplicationEvents1ShortCut(TWMKey &Msg, bool &Handled)
{
    if (Msg.CharCode == VK_F2)
    {
        NTAS0030MClick((TObject*)NTAS0030M);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnRefreshMessage(WPARAM AWParam, LPARAM ALParam)
{
    HWND hWnd;

    // 폴링 스레드에서 데이터베이스 작업 완료후 응답 메시지 처리
    if (AWParam == WP_DB_SELECT_OK)
    {
        DWORD dwTick = GetTickCount();
        switch(ALParam)
        {
        case LP_MSG_TRAFFIC:        DebugMsg(FrmLang->cxLabel3->Caption  + FrmLang->cxLabelRes->Caption); FPollTraffic00.Polling = dwTick; break;
        case LP_MSG_DATABASE_STTS:  DebugMsg(FrmLang->cxLabel25->Caption + FrmLang->cxLabelRes->Caption); FPollDatabase.Polling  = dwTick; break;

        case LP_MSG_FACILITY_STTS:  DebugMsg(FrmLang->cxLabel8->Caption  + FrmLang->cxLabelRes->Caption); FPollStatus01.Polling  = dwTick; break;
        case LP_MSG_PROCESS_STTS:   DebugMsg(FrmLang->cxLabel9->Caption  + FrmLang->cxLabelRes->Caption); FPollStatus02.Polling  = dwTick; break;
        case LP_MSG_INCIDENT:       DebugMsg(FrmLang->cxLabel10->Caption + FrmLang->cxLabelRes->Caption); FPollStatus03.Polling  = dwTick; break;
        case LP_MSG_16: DebugMsg(FrmLang->cxLabel11->Caption + FrmLang->cxLabelRes->Caption); FPollEvent01.Polling   = dwTick; break;
        case LP_MSG_WEATHER:        DebugMsg(FrmLang->cxLabel12->Caption + FrmLang->cxLabelRes->Caption); FPollVilgFrcs.Polling  = dwTick; break;
        case LP_MSG_05: DebugMsg(FrmLang->cxLabel18->Caption + FrmLang->cxLabelRes->Caption); FPollTraffic05.Polling = dwTick; break;

        case LP_MSG_09: DebugMsg(FrmLang->cxLabel15->Caption + FrmLang->cxLabelRes->Caption);  break;  //프로세스정보 재로딩
        case LP_MSG_14: DebugMsg(FrmLang->cxLabel16->Caption + FrmLang->cxLabelRes->Caption);  break;  //시설물정보 재로딩
        }

        if (NITS0000M->Enabled)
        {
            hWnd = FindChildWindow("ITS0000M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }

        if (ALParam == LP_MSG_FACILITY_STTS && NVDSM300M->Enabled)
        {
            hWnd = FindChildWindow("VDSM300M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }

        if (ALParam == LP_MSG_FACILITY_STTS)
        {
            //시설물 상태정보 업데이트
            ShowFacilityStatus();
        }
        else
        if (ALParam == LP_MSG_INCIDENT)
        {
            //돌발발생정보
            //ShowAutoIncidentInfo();
        }
    }
    else
    if (AWParam == WP_MSG_15)
    {
        if (LP_MSG_15 == ALParam)
        {
            DebugMsg("GIS Link Select");
            if (NITS0000M->Enabled)
            {
                hWnd = FindChildWindow("ITS0000M");
                if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
            }
        }
    }
    else
    {
        LOGERROR("DB Thread failed: %02X[%02X]", ALParam, AWParam);
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnDatabaseMessage(WPARAM AWParam, LPARAM ALParam)
{
    HWND hWnd;

    switch(AWParam)
    {
    case WP_MSG_01: //소통등급변경
    case WP_MSG_02: //돌발정보변경(오보/등록/해제)
        if (NITS0000M->Enabled)
        {
            hWnd = FindChildWindow("ITS0000M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        }
        break;
    case WP_MSG_03: //시설물 정보 변경
        DebugMsg(FrmLang->cxLabel16->Caption + FrmLang->cxLabelReq->Caption);
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_14);
        //hWnd = FindChildWindow("ITS0000M");
        //if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);
        break;
    case WP_MSG_04: // IDB0070M-휴일정보
    case WP_MSG_05: // FrmLinkGradeSet-구간등급변경
    case WP_MSG_06: // IDB0060M - 소통등급
    case WP_MSG_07: // IDB0050M -교통파라미터
        //CComm_NodeLinkChangeReq();
        break;
    case WP_MSG_09: // IDB0100M
        DebugMsg(FrmLang->cxLabel12->Caption + FrmLang->cxLabelReq->Caption);
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_09); //작업스레드에서 읽어 처리하도록 한다.

        break;
    case WP_MSG_14: // DSRM010M -DSRC-RSE 관리
        PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_14); //작업스레드에서 읽어 처리하도록 한다.
        break;
    default:
        LOGERROR("Unknown Database Msg: %02X[%02X]", ALParam, AWParam);
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnUdpDataRecvMessage(TMessage &Msg)
{
    int             nResult;
    IPC_MSG_DATA   *RcvData = (IPC_MSG_DATA*)Msg.LParam;
    INT_SENDER     *Sender  = &RcvData->Sender;
    INT_PACKET     *Pkt     = &RcvData->Pkt;
    INT_HEAD       *head    = &Pkt->head;
    INT_DATA       *data    = &Pkt->data;
    char           *pData   = &Pkt->data.Data[0];
    BYTE            OpCode  = head->OpCode;

    LOGINFO("*** OPR Client Req: %s.%d", CComm_ulong2ip(Sender->IP), Sender->Port);

    HWND hWnd;

    bool   bFacility;
    String sMsg      = "";
    String sCtrlNmbr = "";
    TItsFacility *pFacility;
    WPARAM AWParam;
    LPARAM ALParam;

    switch(OpCode)
    {
    case INT_OP_PG_STATE_RES:
        {
            DebugMsg(FrmLang->cxLabel19->Caption);
            INT_PG_STATE_RES *ARes = (INT_PG_STATE_RES*)pData;

            String CommStatus;
            bFacility = false;
            for (int ii = 0; ii < ARes->Count && ii < INT_MAX_PG_STATE; ii++)
            {
                String SYST_ID;
                switch(ARes->Unit[ii].Type)
                {
                case INT_ID_TRAFFIC_SERVER: SYST_ID = "UTP01";  break;
                case INT_ID_VDS_SERVER:     SYST_ID = "VDS01";  break;
                case INT_ID_VMS_SERVER:     SYST_ID = "VMS01";  break;
                case INT_ID_WCAM_SERVER:    SYST_ID = "WCAM01"; break;
                case INT_ID_CCAM_SERVER:    SYST_ID = "CCAM01"; break;
                case INT_ID_EXT01_SERVER:   SYST_ID = "EXT01";  break;
                case INT_ID_EXT02_SERVER:   SYST_ID = "EXT02";  break;
                default: continue;
                }
                TItsProcess *pObj = ItsProcessManager->FLists.Find(SYST_ID);
                if (pObj)
                {
                    CommStatus = ARes->Unit[ii].Action == 0x00 ? "1" : "0";

                    if (pObj->CommStatus != CommStatus) bFacility = true;

                    pObj->CommStatus = CommStatus;
                }
            }
            if (bFacility) OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_PROCESS_STTS);
        }
        break;
    case INT_OP_VMS_STATE_RES:
        {
            INT_VMS_STATE_RES *ARes = (INT_VMS_STATE_RES*)pData;

            sMsg = "";
            sMsg.printf(FrmLang->cxLabel20->Caption.c_str(), ARes->Count);
            DebugMsg(sMsg);

            bFacility = false;
            for (int ii = 0; ii < ARes->Count && ii < INT_VMS_MAX_STATE; ii++)
            {
                sMsg = "";
                INT_VMS_STATE *pVms = &ARes->Unit[ii];
                sCtrlNmbr = String(pVms->VMS_CTLR_NMBR);
                TVmsCtlr *pObj = VmsCtlrManager->FLists.Find(sCtrlNmbr);
                if (pObj)
                {
                    if (pObj->STATE.Comm != pVms->Comm) bFacility = true;

                    memcpy(&pObj->STATE, pVms, sizeof(INT_VMS_STATE));

                    if      (pObj->STATE.OprMode == 'A') pObj->OPER_MODE = "A";
                    else if (pObj->STATE.OprMode == 'B') pObj->OPER_MODE = "B";
                    else                                 pObj->OPER_MODE = "F";

                    pObj->CheckRunState();

                    if (pObj->STATE.Comm != vms_comm_normal)
                    {
                        pObj->VmsMsg->OFFER_YN = false;
                    }

                    pFacility = ItsFacilityManager->FLists.Find(pObj->VMS_CTLR_ID);
                    if (pFacility)
                    {
                        pFacility->FComm = pObj->STATE.Comm == vms_comm_normal ? state_normal : state_error;
                    }
                }
                else
                {
                    sMsg.printf(L"INT_OP_VMS_STATE_RES VMS not found: %s", sCtrlNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            if (bFacility) OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_FACILITY_STTS);
        }
        break;
    case INT_OP_VDS_STATE_RES:
        {
            INT_VDS_STATE_RES *ARes = (INT_VDS_STATE_RES*)pData;

            sMsg = "";
            sMsg.printf(FrmLang->cxLabel26->Caption.c_str(), ARes->Count);
            DebugMsg(sMsg);

            bFacility = false;
            for (int ii = 0; ii < ARes->Count && ii < INT_VDS_MAX_STATE; ii++)
            {
                sMsg = "";
                INT_VDS_STATE *pVds = &ARes->Unit[ii];
                sCtrlNmbr = String(pVds->VDS_CTLR_NMBR);
                TVdsCtlr *pObj = VdsCtlrManager->FLists.Find(sCtrlNmbr);
                if (pObj)
                {
                    if (pObj->STATE.Comm != pVds->Comm) bFacility = true;

                    memcpy(&pObj->STATE, pVds, sizeof(INT_VDS_STATE));

                    pFacility = ItsFacilityManager->FLists.Find(pObj->VDS_CTLR_ID);
                    if (pFacility)
                    {
                        pFacility->FComm = pObj->STATE.Comm == vds_normal ? state_normal : state_error;
                    }
                }
                else
                {
                    sMsg.printf(L"INT_OP_VDS_STATE_RES VDS not found: %s", sCtrlNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            if (bFacility) OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_FACILITY_STTS);
        }
        break;
    case INT_OP_WCAM_STATE_RES:
        {
            INT_WCAM_STATE_RES *ARes = (INT_WCAM_STATE_RES*)pData;

            sMsg = "";
            sMsg.printf(FrmLang->cxLabel27->Caption.c_str(), ARes->Count);
            DebugMsg(sMsg);

            bFacility = false;
            for (int ii = 0; ii < ARes->Count && ii < INT_WCAM_MAX_STATE; ii++)
            {
                sMsg = "";
                INT_WCAM_STATE *pCam = &ARes->Unit[ii];
                sCtrlNmbr = String(pCam->WCAM_CTLR_NMBR);
                TWCamCtlr *pObj = WCamCtlrManager->FLists.Find(sCtrlNmbr);
                if (pObj)
                {
                    if (pObj->STATE.Comm != pCam->Comm) bFacility = true;

                    memcpy(&pObj->STATE, pCam, sizeof(INT_WCAM_STATE));

                    pFacility = ItsFacilityManager->FLists.Find(pObj->WCAM_CTLR_ID);
                    if (pFacility)
                    {
                        pFacility->FComm = pObj->STATE.Comm == wcam_normal ? state_normal : state_error;
                    }
                }
                else
                {
                    sMsg.printf(L"INT_OP_WCAM_STATE_RES WCAM not found: %s", sCtrlNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            if (bFacility) OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_FACILITY_STTS);
        }
        break;
    case INT_OP_CCAM_STATE_RES:
        {
            INT_CCAM_STATE_RES *ARes = (INT_CCAM_STATE_RES*)pData;

            sMsg = "";
            sMsg.printf(FrmLang->cxLabel27->Caption.c_str(), ARes->Count);
            DebugMsg(sMsg);

            bFacility = false;
            for (int ii = 0; ii < ARes->Count && ii < INT_CCAM_MAX_STATE; ii++)
            {
                sMsg = "";
                INT_CCAM_STATE *pCam = &ARes->Unit[ii];
                sCtrlNmbr = String(pCam->CCAM_CTLR_NMBR);
                TCCamCtlr *pObj = CCamCtlrManager->FLists.Find(sCtrlNmbr);
                if (pObj)
                {
                    if (pObj->STATE.Comm != pCam->Comm) bFacility = true;

                    memcpy(&pObj->STATE, pCam, sizeof(INT_CCAM_STATE));

                    pFacility = ItsFacilityManager->FLists.Find(pObj->CCAM_CTLR_ID);
                    if (pFacility)
                    {
                        pFacility->FComm = pObj->STATE.Comm == ccam_normal ? state_normal : state_error;
                    }
                }
                else
                {
                    sMsg.printf(L"INT_OP_CCAM_STATE_RES WCAM not found: %s", sCtrlNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
            if (bFacility) OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_FACILITY_STTS);
        }
        break;
    case INT_OP_VMS_FORM_SAVE:
        {
            //FPollVmsMsg.Reset();    //VMS메시지 조회 타이머 리셋
            char szDateTime[INT_VMS_MAX_DATETIME+1];
            INT_VMS_FORM_SAVE_REQ *AReq = (INT_VMS_FORM_SAVE_REQ*)pData;
            sprintf(szDateTime, "%.*s", INT_VMS_MAX_DATETIME, (char*)AReq->Date);
            String sDateTime = String(szDateTime);
            sMsg = "";
            sMsg.printf(L"*** VMS 폼생성 완료 메시지 수신: %s", sDateTime.c_str());
            DebugMsg(sMsg);
            //OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_VMS_DSPLMSG);
            //VMS다운로드한 결과를 받아서 새로운 VMS스케쥴을 표출하도록 한다.
        }
        break;
    case INT_OP_VMS_FORM_DOWNLOAD:
        {
            OnRefreshMessage(WP_DB_SELECT_OK, LP_MSG_VMS_DSPLMSG);
#if 0
            char szDateTime[INT_VMS_MAX_DATETIME+1];
            char szVmsNmbr[INT_VMS_MAX_ID+1];
            INT_VMS_FORM_DOWNLOAD_REQ *AReq = (INT_VMS_FORM_DOWNLOAD_REQ*)pData;

            sMsg.printf(L"*** VMS 폼 다운로드 메시지 수신: %d EA", AReq->Count);
            DebugMsg(sMsg);

            for (int ii = 0; ii < AReq->Count && ii < INT_VMS_MAX_FORM_DOWNLOAD; ii++)
            {
                sMsg = "";

                INT_VMS_FORM_DOWNLOAD *pVms = &AReq->Unit[ii];
                sprintf(szVmsNmbr, "%.*s", INT_VMS_MAX_ID, (char*)pVms->VmsId);
                sprintf(szDateTime, "%.*s", INT_VMS_MAX_DATETIME, (char*)pVms->Date);

                sCtrlNmbr = String(szVmsNmbr);
                String sDateTime = String(szDateTime);

                TVmsCtlr *pObj = VmsManager->FLists.Find(sCtrlNmbr);
                if (pObj)
                {
                    bool bDnLd = (pVms->Result == vms_download_succ) ? true : false;
                    String sResult = bDnLd ? "Succ" : "Fail";

                    pObj->VmsMsg->OFFER_DT = sDateTime;
                    pObj->VmsMsg->OFFER_YN = bDnLd;

                    for (int kk = 0; kk < pObj->VmsMsg->Total && kk < INT_VMS_MAX_FORM; kk++)
                    {
                        pObj->VmsMsg->PHASE[kk].DNLD_YN = bDnLd ? "Y" : "N";
                    }

                    //sMsg.printf(L"*** ===> VMS Msg download: %s, %s", pObj->VMS_CTLR_ID.c_str(), sResult.c_str());
                    //DebugMsg(sMsg);
                }
                else
                {
                    sMsg.printf(L"*** INT_OP_VMS_FORM_DOWNLOAD VMS not found: %s", sCtrlNmbr.c_str());
                    DebugMsg(sMsg);
                }
            }
#endif
        }
        break;
    case INT_OP_TRAFFIC_CHANGE:       	/* 0x01, 교통정보가공완료 */
        {
            DebugMsg("Traffic Changed");
            FPollTraffic00.Reset(); // 링크소통정보(전체)
        }
        break;
    case INT_OP_NODELINK_CHANGE:    /* 0x10, 노드링크 기반 정보 변경 */
        {
            DebugMsg("Node Link DB Changed");
            //휴일정보
            //구간등급변경
            //소통등급
            //교통파라미터
            /*
            *  기존에는 처리하는것이 없었음.
            *  ---> 심심할때 처리하자
            */
        }
        break;
    case INT_OP_FACILITY_CHANGE:    /* 0x12, 시설물 기반 정보 변경 */
        {
            //CCTV, VMS관련기본정보
            DebugMsg(FrmLang->cxLabel17->Caption);
            PostJobMessage(WM_THREAD, WP_PARAM_TRAFFIC, LP_MSG_14);
        }
        break;
    case INT_OP_VDS_STOP_IMAGE_RES: /* VDS 정지영상 요청 응답 */
        {
            DebugMsg("VDS Stop Image response");
            INT_VDS_STOP_IMAGE_RES *ARes = (INT_VDS_STOP_IMAGE_RES*)pData;
            hWnd = FindChildWindow("VDSM300M");
            if (hWnd) POST_MSG(hWnd, WM_MAINFORM, INT_OP_VDS_STOP_IMAGE_RES, Msg.LParam);
        }
        break;
    }
}
//---------------------------------------------------------------------------
void __fastcall TFrmMain::OnPollingThreadDone(TObject *Sender)
{
    LOGINFO("Polling thead terminated");
    g_AppCfg.thr.bRunning = false;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::ShowFacilityStatus()
{
//    HWND hWnd = FindChildWindow("ITS0000M");
//    if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);

    bool bShow = false;
    try
    {
        try
        {
            ItsFacilityManager->FLists.Lock();
            FOR_STL(TItsFacility*, pFacility, ItsFacilityManager->FLists)
            {
                if (pFacility->DEL_YN == "Y") continue;

#if 0
                if (pFacility->FCLT_TYPE == "DSRC")
                {
                    if (pFacility->FCollCntBase > pFacility->FCollCntCurr)
                    {
                        bShow = true;
                        break;
                    }
                }
#endif

                if (pFacility->FComm != state_normal)
                {
                    bShow = true;
                    break;
                }
                else
                {
#if 0
                    try
                    {
                        String sValue = pFacility->FCBoxTmpr;
                        int nValue = 0;
                        if (TryStrToInt(sValue, nValue))
                        {
                            if (nValue > g_AppCfg.Temp.AlarmValue)
                            {
                                bShow = true;
                                break;
                            }
                        }
                    } catch(...) {}
#endif
                }
            }
        }
        __finally
        {
            ItsFacilityManager->FLists.UnLock();
        }
    }
    catch(...)
    {
    }

    if (!bShow)
    {
        LblAlarm->Style->Font->Color = clBlack;
        //LblAlarm->Caption = "알람정보";
        LblAlarm->Caption = FrmLang->cxLabel21->Caption;
        ImgAlarm->Visible = false;
        ImgAlarmNormal->Visible = true;
        try {
            if (ImgAlarm->Picture->Graphic->ClassName() == "TGIFImage")
                ((TGIFImage *)ImgAlarm->Picture->Graphic)->Animate = false;
        } catch(...) {}
        return;
    }

    ImgAlarmNormal->Visible = false;
    ImgAlarm->Visible = true;
    try {
        if (ImgAlarm->Picture->Graphic->ClassName() == "TGIFImage")
            ((TGIFImage *)ImgAlarm->Picture->Graphic)->Animate = true;
    } catch(...) {}
    //LblAlarm->Caption = "알람발생";
    LblAlarm->Caption = FrmLang->cxLabel22->Caption;
    LblAlarm->Style->Font->Color = clRed;

    if (!g_AppCfg.Alarm.Enabled) return;
    if (!g_AppCfg.Alarm.Window) return;


    try
    {
        if (FrmFacilityAlarm == NULL)
        {
            FrmFacilityAlarm = new TFrmFacilityAlarm(Application);
        }
        FrmFacilityAlarm->Show();
        FrmFacilityAlarm->ShowFacilityAlarm();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::ShowAutoIncidentInfo()
{
//    HWND hWnd = FindChildWindow("ITS0000M");
//    if (hWnd) POST_MSG(hWnd, WM_MAINFORM, AWParam, ALParam);

    if (!g_AppCfg.Incident.Enabled) return;

    bool bShow = false;
    try
    {
        try
        {
            ItsIncidentManager->FAutoLists.Lock();

            if (ItsIncidentManager->FAutoLists.Size() > 0)
            {
                bShow = true;
            }
        }
        __finally
        {
            ItsIncidentManager->FAutoLists.UnLock();
        }
    }
    catch(...)
    {
    }

    if (!bShow) return;

    try
    {
        if (FrmIncidentAlarm == NULL)
        {
            FrmIncidentAlarm = new TFrmIncidentAlarm(Application);
        }
        FrmIncidentAlarm->Show();
        FrmIncidentAlarm->ShowIncidentAlarm();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH010MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH020MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH030MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH030M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH040MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH040M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH050MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH050M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRM010MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRM010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRM020MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRM020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRM030MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRM030M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRM040MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRM040M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH010MClick(TObject *Sender)
{
    FORMSHOW(VDSH010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH020MxClick(TObject *Sender)
{
    FORMSHOW(VDSH020M);
}
//---------------------------------------------------------------------------

/*
 * VDS-검지기 과거수집이력화면 호출
 */
void __fastcall TFrmMain::NVDSH030MxClick(TObject *Sender)
{
    FORMSHOW(VDSH030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH040MClick(TObject *Sender)
{
    FORMSHOW(VDSH040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH050MxClick(TObject *Sender)
{
    FORMSHOW(VDSH050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSS010MClick(TObject *Sender)
{
    FORMSHOW(VDSS010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSS020MClick(TObject *Sender)
{
    FORMSHOW(VDSS020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIM010MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIM010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIM020MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIM020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH010MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH020MxClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH030MxClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH030M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH040MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH040M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH050MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH050M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH060MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH060M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH070MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH070M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIS010MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIS010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIS020MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIS020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NSMS0010MClick(TObject *Sender)
{
    //FORMSHOW(SMS0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NSMS0020MClick(TObject *Sender)
{
    //FORMSHOW(SMS0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NSMS0030MClick(TObject *Sender)
{
    //FORMSHOW(SMS0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIFM0040MClick(TObject *Sender)
{
    FORMSHOW(IFM0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIFM0050MClick(TObject *Sender)
{
    FORMSHOW(IFM0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NPIS0010MClick(TObject *Sender)
{
#ifdef USE_PARK
    FORMSHOW(PIS0010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NPIS0030MClick(TObject *Sender)
{
#ifdef USE_PARK
    FORMSHOW(PIS0030M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NPIS0020MClick(TObject *Sender)
{
#ifdef USE_PARK
    FORMSHOW(PIS0020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NPISH010MClick(TObject *Sender)
{
#ifdef USE_PARK
    FORMSHOW(PISH010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NPISH020MClick(TObject *Sender)
{
#ifdef USE_PARK
    FORMSHOW(PISH020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH060MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH060M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NDSRH070MClick(TObject *Sender)
{
#ifdef USE_DSRC
    FORMSHOW(DSRH070M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::OnAlarmDblClick(TObject *Sender)
{
    try
    {
#if 0
//TODO
if (FrmIncidentAlarm == NULL)
{
    FrmIncidentAlarm = new TFrmIncidentAlarm(Application);
}
FrmIncidentAlarm->Show();
FrmIncidentAlarm->ShowIncidentAlarm();
#endif
        if (FrmFacilityAlarm == NULL)
        {
            FrmFacilityAlarm = new TFrmFacilityAlarm(Application);
        }
        FrmFacilityAlarm->Show();
        FrmFacilityAlarm->ShowFacilityAlarm();
    }
    catch(...)
    {
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0060MClick(TObject *Sender)
{
    FORMSHOW(IHS0060M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIHS0070MClick(TObject *Sender)
{
    FORMSHOW(IHS0070M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::TmrDbCheckTimer(TObject *Sender)
{
    TmrDbCheck->Enabled = false;

    if (ITSDb_IsOpen() == false)
    {
        //DebugMsg("데이터베이스 연결 오류....");
        DebugMsg(FrmLang->cxLabel23->Caption);
        UpdateDbStatus(true);
        if (DbConnect())
        {
            if (ITSDb_Open())
            {
                UpdateDbStatus(false);
                //DebugMsg("데이터베이스 재연결 성공....");
                DebugMsg(FrmLang->cxLabel24->Caption);
            }
        }
        TmrDbCheck->Interval = 10000;
    }
    else
    {
        if (IsDbAlive())
        {
            TmrDbCheck->Interval = 10000;
        }
        else
        {
            TmrDbCheck->Interval = 5000;
        }
    }
    TmrDbCheck->Enabled = true;
}
//---------------------------------------------------------------------------
bool __fastcall TFrmMain::DbConnect()
{
    TADOConnection *m_pConnection = new TADOConnection(NULL);
    try
    {
        try
        {
            m_pConnection->ConnectionString	= ITSDb_GetConnStr();
            m_pConnection->KeepConnection	= true;
            m_pConnection->LoginPrompt		= false;
            m_pConnection->Open();
            m_pConnection->Close();
        }
        catch(EDatabaseError &E)
        {
            return false;
        }
        catch (Exception &e)
        {
            return false;
        }
        catch (...)
        {
            return false;
        }
    }
    __finally
    {
        SAFE_DELETE(m_pConnection);
    }

    return true;
}
//---------------------------------------------------------------------------
bool __fastcall TFrmMain::IsDbAlive()
{
    String     sQry;
    TADOQuery *pADO = NULL;
    try
    {
        sQry = "SELECT TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') AS CURDATE FROM DUAL";

        try
        {
            pADO = new TADOQuery(NULL);
			pADO->Close();
            pADO->Connection = ITSDb_GetConnection();

			pADO->SQL->Clear();
			pADO->SQL->Text = sQry;
            pADO->Prepared = true;
			pADO->Open();

            for( ; !pADO->Eof; pADO->Next())
            {
                String sCurrDate = pADO->FieldByName("CURDATE")->AsString;
            }
        }
        catch (Exception &exception)
        {
            ITSDb_Close();
            return false;
        }
	}
	__finally
	{
        if (pADO)
        {
            pADO->Close();
            delete pADO;
        }
	}
    return true;
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NBDS0010MClick(TObject *Sender)
{
#ifdef D_BLACKBOX
    FORMSHOW(BDS0010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NBDS0020MClick(TObject *Sender)
{
#ifdef D_BLACKBOX
    FORMSHOW(BDS0020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NBDH0010MClick(TObject *Sender)
{
#ifdef D_BLACKBOX
    FORMSHOW(BDSH010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NBDH0020MClick(TObject *Sender)
{
#ifdef D_BLACKBOX
    FORMSHOW(BDSH020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0010MClick(TObject *Sender)
{
    FORMSHOW(TAS0010M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0020MClick(TObject *Sender)
{
    FORMSHOW(TAS0020M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0030MClick(TObject *Sender)
{
    FORMSHOW(TAS0030M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0040MClick(TObject *Sender)
{
    FORMSHOW(TAS0040M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0050MClick(TObject *Sender)
{
    FORMSHOW(TAS0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0060MClick(TObject *Sender)
{
    FORMSHOW(TAS0060M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0070MClick(TObject *Sender)
{
    FORMSHOW(TAS0070M);
}
//---------------------------------------------------------------------------
void __fastcall TFrmMain::NTAS0080MClick(TObject *Sender)
{
    FORMSHOW(TAS0080M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTAS0090MClick(TObject *Sender)
{
    FORMSHOW(TAS0090M);
}
//---------------------------------------------------------------------------


void __fastcall TFrmMain::NWBH0010MClick(TObject *Sender)
{
#ifdef D_WBH0010M
    FORMSHOW(WBH0010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NAVIH080MClick(TObject *Sender)
{
#ifdef USE_AVI
    FORMSHOW(AVIH080M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NIDB0140MClick(TObject *Sender)
{
#ifdef D_IDB0140M
    FORMSHOW(IDB0140M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NITS0050MClick(TObject *Sender)
{
//    FORMSHOW(ITS0050M);
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSM100MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSM100M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSM020MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSM200M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NWCAM100MClick(TObject *Sender)
{
#ifdef USE_WCAM
    FORMSHOW(WCAM100M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NWCAM010MClick(TObject *Sender)
{
#ifdef USE_WCAM
    FORMSHOW(WCAM010M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSM000MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSM000M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH070MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSH070M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSH080MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSH080M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NWCAMH10MClick(TObject *Sender)
{
#ifdef USE_WCAM
    FORMSHOW(WCAMH10M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NVDSM300MClick(TObject *Sender)
{
#ifdef USE_VDS
    FORMSHOW(VDSM300M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NCCAM100MClick(TObject *Sender)
{
#ifdef USE_CCAM
    FORMSHOW(CCAM100M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NCCAMH10MClick(TObject *Sender)
{
#ifdef USE_CCAM
    FORMSHOW(CCAMH10M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NCCAM020MClick(TObject *Sender)
{
#ifdef USE_CCAM
    //FORMSHOW(CCAM020M);
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::NTST0000MClick(TObject *Sender)
{
#if 0
    String sExeName = "Project1.exe";
    String sParam   = "\"" + g_pLOGIN->sUserId + "\" \"" + g_pLOGIN->sUserId + "\"";
    //ShellExecute(NULL,"open", "C:\\myprocess.exe", "\"my argument 1 containing spaces\" \"my argument 2\"","C:\\",SW_SHOWNORMAL);

    ShellExecute(Handle, NULL, sExeName.c_str(), sParam.c_str(), NULL, SW_SHOWNORMAL);
#endif

#include <stdio.h>
    AnsiString sQry1 = "INSERT INTO TB_OPERSYST_MENU VALUES('%s', '%02d.%s', 'N', 1, '');\n";
    AnsiString sQry2 = "INSERT INTO TB_OPERSYST_MENU VALUES('%s', '%s', 'N', 2, '%s');\n";
    AnsiString sMenuFile = g_sAppDir + "Menu.TXT";
    FILE      *pFileMenu = NULL;
    pFileMenu = fopen(sMenuFile.c_str(), "w+");
    if (pFileMenu == NULL)
    {
        ShowMessage("메뉴파일을 생성하지 못하였습니다.");
        return;
    }

    int nMenuCnt = 1;
    int nMenuTabs = Ribbon->Tabs->Count;
    for (int ii = 0; ii < nMenuTabs; ii++)
    {
        TdxRibbonTab *pTab = Ribbon->Tabs->Items[ii];
        if (pTab->Visible == false) continue;

        AnsiString sMainName = pTab->Name;
        AnsiString sMainCap  = pTab->Caption;
        fprintf(pFileMenu, sQry1.c_str(), sMainName.c_str(), nMenuCnt++, sMainCap.c_str());

        int nSubMenus = pTab->Groups->Count;
        for (int jj = 0; jj < nSubMenus; jj++)
        {
            TdxRibbonTabGroup *pGroup = pTab->Groups->Items[jj];
            TdxBar *pBar = pGroup->ToolBar;
            if (pBar->Visible == false) continue;

            int nMenus = pBar->ItemLinks->Count;
            for (int kk = 0; kk < nMenus; kk++)
            {
                TdxBarItemLink *pItemLink = pBar->ItemLinks->Items[kk];
                TdxBarLargeButton *pMenuBtn = (TdxBarLargeButton*)pItemLink->Item;
                if (pMenuBtn->Visible != ivAlways) continue;

                AnsiString sMenuName = pMenuBtn->Name;
                AnsiString sMenuCap  = pMenuBtn->Caption;
                fprintf(pFileMenu, sQry2.c_str(), sMenuName.c_str(), sMenuCap.c_str(), sMainName.c_str());
            }
        }
    }

    fclose(pFileMenu);
    pFileMenu = NULL;
#if 0
                    for (int ii = 0; ii < nCompnentCnt; ii++)
                    {
                        String sClassName = this->Components[ii]->ClassName();
                        if(sClassName == "TdxBarLargeButton")
                        {
                            TdxBarLargeButton *pMenu = (TdxBarLargeButton *)this->Components[ii];
                            if (pMenu->Name == sMenuId)
                            {
                                pMenu->Enabled = false;
                                break;
                            }
                        }
                    }
#endif
}
//---------------------------------------------------------------------------

void __fastcall TFrmMain::FormDblClick(TObject *Sender)
{
    NTST0000MClick((TObject*)NTST0000M);
}
//---------------------------------------------------------------------------

