C++(MFC, ETC) 모음

from Study/C++ 2009/02/25 12:27 view 45865
1.cpp
/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 콘트롤 -  ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

//---List Box / file Dir Dlg--------------------------------------------------------

 //----------------------------------------------------------------------------
         // 폴더 얻기
   char szTemp[255];
     memset(szTemp, 0, 255);
     lstrcat(szTemp, "c:\\Data");
     CDialog::DlgDirList(szTemp, IDC_LISTBOX, NULL, DDL_EXCLUSIVE | DDL_DIRECTORY);
  //----------------------------------------------------------------------------

  //----------------------------------------------------------------------------
         //화일명 얻기
  CString Path_Log="C:\\WaterSensor성능검사기\\Data\\";
  CString ss=""; CString tt="";
  
      tt="*.mdb";
  ss =Path_Log+"*.mdb";
 
  char szTemp[255];
  memset(szTemp, 0, 255);
  lstrcat(szTemp, ss);
  CDialog::DlgDirList(szTemp, IDC_SLOG_LIST, NULL, NULL);// DDL_EXCLUSIVE | DDL_DIRECTORY);

  int nList=0; CString csTmp="";
  sLog.SetCurSel(nList);
/*
  if(sLog.GetTextLen(nList)>0)
  {
   sLog.GetText(nList ,csTmp);
   if( FileExists(Path_Log+csTmp))
   {
       ss=LoadReadFile(Path_Log+csTmp);
       LogDisplay(ss);
   }
  }
*/

//==============================================================================
//---다른 Label 콘트롤(Threed32 Panel) Control 상속 얻기 -----------------------

 #include "sspnctrl.h"

 CSSPNCtrl *Static;
 Static = (CSSPNCtrl *)GetDlgItem(IDC_IO_0);
 Static->SetBackColor(0x0000ff); //BGR

void CAttachMachineView::Sub_SetDlgItemColor(int nID, COLORREF CColor)
{
 CSSPNCtrl *Static;
 Static = (CSSPNCtrl *)GetDlgItem(IDC_IO_0);
 Static->SetBackColor(CColor);
}

 CSSPNCtrl *Static;
 Static = (CSSPNCtrl *)GetDlgItem(IDC_EXIT_WAITE_MESSAGE);
 Static->ShowWindow(true);

 #include "LabelControl.h"
 ((CLabelControl*)GetDlgItem(nID))->SetBackColor(OK_COLOR);


//---Control 상속 보이기--------------------------------------------------------

 CButton *pBtn;
 pBtn = (CButton *)GetDlgItem(IDC_CLOSE_BTN);
 pBtn->ShowWindow(true);

 Static = (CStatic *)GetDlgItem(IDC_CAM_NAME);
 Static->ShowWindow(true);


//---Control 이벤트--------------------------------------------------------
 .h
 //{{AFX_MSG(CImageViewView)
 afx_msg bool OnClickImageView(UINT nID);
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
 .cpp
 BEGIN_MESSAGE_MAP(CImageViewView, CFormView)
 //{{AFX_MSG_MAP(CImageViewView)
 ON_COMMAND_RANGE(IDC_IMG_VIEW1, IDC_IMG_VIEW4, OnClickImageView)
   END_MESSAGE_MAP()
 
 bool CImageViewView::OnClickImageView(UINT nID)
 {
 CString csTmp;
 csTmp.Format("%d",nID);
 AfxMessageBox(csTmp);
 return true;
 }


 #define OK_COLOR  RGB(100,150,255)
 #define NG_COLOR  RGB(235,60,60)
 COLORREF clLime;

 //--Inage List
 BOOL bRetValue = FALSE;
 HICON hIcon = NULL;
// m_CurLibType = m_SelLibrary = m_SleLibType = LINE2RECT;


 SetIcon(m_hIcon, TRUE);
 SetIcon(m_hIcon, FALSE);

 // Create image list
 bRetValue = m_ImageList.Create(80, 80, ILC_COLOR32 | ILC_MASK, 5, 1);
 ASSERT(bRetValue == TRUE);

 // Add some icons
 hIcon = AfxGetApp()->LoadIcon(IDI_ICON_MARK);
 m_ImageList.Add(hIcon);

 m_lbxListBox.SetImageList(&m_ImageList);

//--CShadeButton------------------------------------------------------
 #include "ShadeButtonST.h"
 
 .h --
 CShadeButtonST m_btnXYOrg;
 
 ..cpp
 DDX_Control(pDX,IDC_BTN_XYORG,m_btnXYOrg);  //IDC_BTN_XYORG 푸시 버튼
 
 ..OnInitDialog()
 //COLORREF crBtnColor;
 //crBtnColor = ::GetSysColor(COLOR_ACTIVEBORDER) + RGB(100, 50, 50);
 m_btnXYOrg.SetShade(CShadeButtonST::SHS_HBUMP);
 
 //-------
 m_btnXYOrg.SetShade(CShadeButtonST::SHS_HSHADE);
 m_btnXYOrg.Invalidate();
 m_btnXYOrg.SetShade(CShadeButtonST::SHS_HSHADE,8,10,30,RGB(100,55,0));
 
 
 
 //--CLabelControl--------------------------------------------------

 CLabelControl *pLabel;
 for(int i=0; i<MAX_ONE_BD-2; i++)//0-5 Label1 - Label6
 {
  pLabel = (CLabelControl *)GetDlgItem(IDC_LABEL1+i);
  pLabel->SetEnabled(FALSE);
 }
 //Label7 ID가 순서대로가 아님
 pLabel = (CLabelControl *)GetDlgItem(IDC_LABEL7);
 pLabel->SetEnabled(FALSE);

 CComboBox *pcbo;
 pcbo = (CComboBox *)GetDlgItem(IDC_COMBO_SELECT_AXIS);
 m_SelectAxisNo = pcbo->SetCurSel(0);

 pcbo = (CComboBox *)GetDlgItem(IDC_COMBO_SELECT_MODE);
 m_SelectAxisMode= pcbo->SetCurSel(0);
 pcbo->EnableWindow(false);

 CStatic *Static;
 Static = (CStatic *)GetDlgItem(IDC_STATIC_AXIS_MODE);
 Static->EnableWindow(false);//Static->ShowWindow(false);

 CButton *pchk;
 pchk = (CButton *)GetDlgItem(IDC_RADIO_MMCBOARD1);
 pchk->SetCheck(TRUE);

 // Axis One Select LED Status
 m_ledOpSelect1.SetValue(false); m_ledOpSelect2.SetValue(false);m_ledOpSelect3.SetValue(true);

/*------Combo Box---------------------------------------------------*/

 CComboBox *pcbo2;
 pcbo2 = (CComboBox *)GetDlgItem(IDC_COMBO_SELECT_MODE);
 m_SelectAxisMode = pcbo2->SetCurSel(0);

/*------이벤트 얻기---------------------------------------------------*/

BOOL CManualMotorPage::PreTranslateMessage(MSG* pMsg)
{
 // TODO: Add your specialized code here and/or call the base class
 int ret;
 CLabelControl *plbl;
 if(pMsg->message == WM_LBUTTONDOWN){
  for(int i=0;i<MAX_AXIS;i++){
 
   plbl = (CLabelControl *)GetDlgItem(IDC_LBL_AXIS_X+i);
   if(pMsg->hwnd == plbl->m_hWnd){
   
     return TRUE;
    }
   }
  }
 }
 return CPropertyPage::PreTranslateMessage(pMsg);
}

/*------Icon---------------------------------------------------*/

 HICON m_hIconOnOff[2];

 m_hIconOnOff[0] = AfxGetApp()->LoadIcon(IDI_OFF);
 m_hIconOnOff[1] = AfxGetApp()->LoadIcon(IDI_ON);


 CStatic *icon;

 icon = (CStatic *)GetDlgItem(IDC_PIC_LED1);
 icon->SetIcon(m_hIconOnOff[0]);

/*------Button Enable-----------------------------------------------------*/

 CButton *opBtn;
 opBtn=(CButton *)GetDlgItem(IDC_BTN_START);
 opBtn->EnableWindow(FALSE);
 CCommandButton *origBtn;
 origBtn=(CCommandButton *)GetDlgItem(IDC_CMD_ORIG_START);
 origBtn->SetEnabled(FALSE);

/*------Microsoft Form2.0 Check Box Set------------------------------------*/

// void SetValue(VARIANT* newValue);
 void SetValue( BOOL newValue);
// VARIANT GetValue();
 BOOL GetValue();
void CMdcCheckBox::SetValue(BOOL newValue)
{
 static BYTE parms[] =
  VTS_BOOL;
 InvokeHelper(0x0, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
   newValue);
}
BOOL CMdcCheckBox::GetValue()
{
 BOOL result;
 InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
 return result;
}

 CMdcCheckBox *pchk;
 pchk = (CMdcCheckBox *)GetDlgItem(IDC_CHECKBOX1);
 pchk->SetValue(true);

 CMdcCheckBox *pchk;
 pchk = (CMdcCheckBox *)GetDlgItem(IDC_CHECKBOX1);
 if(pchk->GetValue())AfxMessageBox("on");
 else AfxMessageBox("off");

/*------Radio Button Set---------------------------------------------------*/

 CButton *pchk;
 pchk = (CButton *)GetDlgItem(IDC_RADIO_NONE);
 pchk->SetCheck(FALSE);
 pchk = (CButton *)GetDlgItem(IDC_RADIO_SPLIT);
 pchk->SetCheck(TRUE);
/*------------------------------------------------------------------------*/

/*------어레이 이벤트 발생 설정 ------------------------------------------*/
   ..h
 protected:
 //}}AFX_MSG
 afx_msg void OnChangeTray(UINT nID);
 DECLARE_MESSAGE_MAP()

   ..cpp
 BEGIN_MESSAGE_MAP(CPreMountDataPage, CPropertyPage)
 //}}AFX_MSG_MAP
 ON_COMMAND_RANGE(IDC_RADIO_TRAY1, IDC_RADIO_TRAY4, OnChangeTray)
 END_MESSAGE_MAP()

void CPreMountDataPage::OnChangeTray( UINT nID )
{
 CLabelControl *label;
 UpdateData(TRUE);
 m_nTrayNo = nID - IDC_RADIO_TRAY1;
}


/*------Gride Scroll-----------------------------------------------------*/
 m_MSFlexGrid.SetScrollTrack(true);


/*------Icon 불러오기-----------------------------------------------------*/

  IDC_PIC_LED1 : Picture Properties, Type -Icon

 HICON m_hIconOnOff[2];

 m_hIconOnOff[0] = AfxGetApp()->LoadIcon(IDI_OFF);
 m_hIconOnOff[1] = AfxGetApp()->LoadIcon(IDI_ON);

 CStatic *icon;
 for(int i=0; i<9; i++) {
  icon = (CStatic *)GetDlgItem(IDC_PIC_LED1 + i);
  icon->SetIcon(m_hIconOnOff[0]);
 }

/*------다중 콘트롤 ID 지정 및 얻기----------------------------------------*/

DeviceCheckView.h 화일

//}}AFX_MSG
DECLARE_MESSAGE_MAP()
afx_msg void OnChangeIoNo( UINT nID );
//-----

DeviceCheckView.cpp 화일

void CDeviceCheckView::DoDataExchange(CDataExchange* pDX)
{
 CFormView::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CDeviceCheckView)
 DDX_Radio(pDX, IDC_IONO1, m_nioNo);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDeviceCheckView, CFormView)
 //{{AFX_MSG_MAP(CDeviceCheckView)
 ON_WM_TIMER()
 //}}AFX_MSG_MAP
 ON_COMMAND_RANGE(IDC_IONO1, IDC_IONO6, OnChangeIoNo)
END_MESSAGE_MAP()

void CDeviceCheckView::OnChangeIoNo( UINT nID )
{
 m_nioNo = nID - IDC_IONO1;
}


/*------콘트롤 ID 지정 및 얻기---------------------------------------------*/
//--------------------------------------------------------------------------
 ON_EVENT(CIODisplay, IDC_OUT_T0, -600 /* Click */, OnClickOutBtn, VTS_NONE)
 ON_EVENT(CIODisplay, IDC_OUT_T1, -600 /* Click */, OnClickOutBtn, VTS_NONE)
 ON_EVENT(CIODisplay, IDC_OUT_T2, -600 /* Click */, OnClickOutBtn, VTS_NONE)

void CIODisplay::OnClickOutBtn()
{
 int id = GetFocus()->GetDlgCtrlID() - IDC_OUT_T0;
}
//--------------------------------------------------------------------------

/*------상속받아 콘트롤변수지정---------------------------------------------*/
 #include "xShadeButton.h"
 #include "SXButton.h"
 DDX_Control(pDX, IDC_ESTOP, m_EStop);
 m_EStop.SetIcon( IDI_ESTOP, 32, 32 );
 m_EStop.SetImagePos( CPoint ( 2, SXBUTTON_CENTER ) );
 m_EStop.SetTextPos( CPoint ( 28, SXBUTTON_CENTER ) );
 m_EStop.SetFont(&m_sFont);

/*------상속받아 콘트롤 설정  ---------------------------------------------*/
 #include "EditEx.h"
 CEditEx m_CmdPos[2];
 m_CmdPos[0].SubclassDlgItem(IDC_CMD_POS0, this);
 m_CmdPos[0].bkColor( BLACK );
 m_CmdPos[0].textColor( YELLOW );
 m_CmdPos[0].setFont( 10, FW_ULTRABOLD, DEFAULT_PITCH | FF_DONTCARE, _T("궁서"));
 m_CmdPos[0].SetWindowText("0.000");


 SetDlgItemDouble(IDC_CMD_POS0, cmd_pos[0]);


// 지정한 컨트롤에 값을 보여준다.
void CCAMCFS20Dlg::SetDlgItemDouble(int nID, double value)
{
 CString sTemp;
 sTemp.Format("%.3f", value);
 GetDlgItem(nID)->SetWindowText(sTemp);
}

// 지정한 컨트롤에서 값을 읽어온다.
double CCAMCFS20Dlg::GetDlgItemDouble(int nID)
{
 double dRet;
 CString sTemp;
 GetDlgItem(nID)->GetWindowText(sTemp);
 dRet = atof((LPCTSTR)sTemp);

 return dRet;
}

/*------EnableWindow--------------------------------------------------------*/
 EnableWindow(GetDlgItem(m_hDlg,IDC_BTN_START),FALSE);
 EnableWindow(GetDlgItem(m_hDlg,IDC_BTN_STOP),TRUE);

 char szBuf[256];
 SetDlgItemText(m_hDlg, IDC_MSG, "Server Running");
 GetDlgItemText(m_hDlg,IDC_LISTEN_EDIT,szBuf,256);
 
 int iPort = atoi(szBuf);
 memset(szBuf,0,256);

/*------EDIT CONTROL--------------------------------------------------------*/
void CWinDlg::WriteText(char* szData)
{
 HWND hWndOutput;
 int iChar;
 
 hWndOutput = GetDlgItem(m_hDlg, IDC_EDIT_BOARD);
 iChar = SendMessage(hWndOutput, EM_GETLIMITTEXT, 0, 0);
 SendMessage(hWndOutput, EM_SETSEL, iChar, iChar);
 SendMessage(hWndOutput, EM_REPLACESEL, FALSE, (LPARAM)szData);
 SendMessage(hWndOutput, EM_REPLACESEL, FALSE, (LPARAM)"\r\n");
}

/*------Control Key--------------------------------------------------------*/
 #define VK_NUMLOCK        0x90
 #define VK_SCROLL         0x91

 KeyCode=GetKeyState(VK_CONTROL);
 if((KeyCode==CONTROLKEY1)||(KeyCode==CONTROLKEY2)){bConKey=TRUE;}

/*------Read Only----------------------------------------------------------*/
 m_FileSaveAsButton[nCh].EnableWindow(FALSE);
 m_ItemSelectCombo[nCh].EnableWindow(nMode);
 m_SetRevCheckBox[nCh].EnableWindow(nMode);
 m_TestViasstatic[nCh].SetReadOnly(nMode);

/*------Slider------------------------------------------------------------*/

 m_SpotTopSlider.GetPos();//일반
// m_SpotLeftSlider.SetRange(0, 1024);//일반
 m_SpotLeftSlider.SetValue(140);    //NI 콘트롤

void CGraphResultPage3::OnPointerValueChangedSpotBottomSlider(long Pointer, VARIANT FAR* Value)
{
 // TODO: Add your control notification handler code here
 int nData=0;
 nData = CNiVariant(Value);m_nSpotBottomLimit=nData;
}

/*------Message------------------------------------------------------------*/

// MessageBox(NULL,buf,title,MB_OK|MB_ICONEXCLAMATION);

// if (MessageBox("Module Aging Program Quit? ", " OLED Module Aging Program",
//  /*MB_ICONQUESTION*/MB_ICONSTOP | MB_OKCANCEL) == IDOK)  {
// OnClose();
// PostQuitMessage(0);
// }

 RedrawWindow();//Invalidate(FALSE);

/*------ 콘트롤 Bmp-------------------------------------------------------------------*/
 CBitmap m_ButtonBmp1;
 m_ButtonBmp1.LoadBitmap(IDB_SAVEBUTTONBMP);
 m_FileSaveAsButton[0].SetBitmap(m_ButtonBmp1);
 RedrawWindow();//Invalidate(FALSE);

/*------ 콘트롤 Enable----------------------------------------------------------------*/
 m_ccEdit1.SetReadOnly(TRUE);
 m_ccButton1.EnableWindow(TRUE);

 m_ccModeCheck1.ShowWindow(SW_SHOW);
 m_ccModeCheck2.ShowWindow(SW_HIDE);
/*------------------------------------------------------------------------------------*/
/*------CT 콘트롤 제어----------------------------------------------------------------*/
 m_cttPosition11.SetBackColor(RGB(255,0,0));
 m_cttPosition11.SetForeColor(RGB(255,0,0));
 m_cttPosition11.SetCaption("-120.000");
 m_cttPosition11.ShowWindow(FALSE);

/*------NI 콘트롤 숨김----------------------------------------------------------------*/

 m_nctlTestButton1.ShowWindow(FALSE);//숨김

/*------NI Graph----------------------------------------------------------------*/

 m_ResultLineGraph1.GetAxes().Item(3.0).GetTicks().SetMajorTickColor(White);
 m_ResultLineGraph1.GetPlots().Item(2.0).SetLineColor(White);
 m_ResultLineGraph1.GetAxes().Item(1).GetLabels().SetColor(White);

 m_ResultLineGraph1.GetAxes().Item(1).AutoScaleNow();
 m_ResultLineGraph1.GetAxes().Item(2).AutoScaleNow();

 m_ResultLineGraph1.GetAxes().Item(1).SetMinMax(m_GraphScaleMin_x,m_GraphScaleMax_x);
 m_ResultLineGraph1.GetAxes().Item(2).SetMinMax(m_GraphScaleMin_y,m_GraphScaleMax_y);


//==================================================================================
/*------DlgList [..][]------------------------------------------------------------*/
  char szTemp[255];
     memset(szTemp, 0, 255);
     lstrcat(szTemp, "c:\\Data");
     CDialog::DlgDirList(szTemp, IDC_LISTBOX, NULL, DDL_EXCLUSIVE | DDL_DIRECTORY);
 

/*----------------------------------List Box Text 얻기----------------------------*/
//=================================================================================
 CString strTmp="";
 int nListNo=m_ccName.GetCurSel();
 
 if(m_ccName.GetTextLen(nListNo)>0)
 {
  m_ccName.GetText(nListNo,strTmp);
 }

 m_ccModuleMeasureList.InsertString(nListNo,csFind);


 nListNo=m_ccImageList.GetCurSel();
 
 CString csFind;m_ccImageList.GetText(nListNo,csFind);
 nListNo=m_ccModuleMeasureList.GetCurSel();
 m_ccModuleMeasureList.DeleteString(nListNo);
 m_ccModuleMeasureList.InsertString(nListNo,csFind);
 
 
 int nListMax=flBox.GetCount();
 csTmp.Format("%d",nListMax); AfxMessageBox(csTmp);


 
//==================================================================================

/*----------------------------------Multi Edit 한줄씩 얻기----------------------------*/
 CString ReadData; CString strTmp="";
 GetDlgItemText(IDC_INSTRUCT_EDIT, ReadData);
 int index=0; int length=0;
 char chBuf[2];


 length = ReadData.GetLength();
 int nListCount=0;

 CString csLineData[CHMAX];
 CString csBuf=_T("");

 for(int i=0; i<length; i++)
 {
  csBuf=ReadData.Mid(i,1);
  if(csBuf=="\n")
  {
   csBuf="";
   nListCount++;
  }
  else
  {
   if(csBuf!="\r")
   {
   chBuf[0]=csBuf.GetAt(0);
   chBuf[1]='\0';
   csLineData[nListCount]+=chBuf;
   }
  }
 }

 for(int n=0; n<nListCount+1; n++)
 AfxMessageBox(csLineData[n]);


/*----------------------------------콘트롤 생성-------------------------------------*/
// CComboBox m_pComboBox[CHMAX];
// CEdit m_pEditBox[CHMAX];
// CListBox m_pListBox[CHMAX];
// CButton m_pButton[CHMAX];

 WS_THICKFRAME  콘트롤 크기 가변

 RECT ovlScrRect;
 m_Display.GetWindowRect(&ovlScrRect);
 ::CopyRect(&OverlayClientRect,&ovlScrRect);
 ScreenToClient(&OverlayClientRect);

 pVision->OutputOverlay(GetDC()->m_hDC,&ovlScrRect);
 UpdateOverlayWindow();

/* CStatic *m_static;
 m_static = new CStatic;
 m_static->Create(_T("스태틱"),
     WS_VISIBLE | SS_CENTER,
     CRect(10,10,210,40),
     this,
     ID_SAMPLE_STATIC1);
*/

 //리스트 박스 만들기
 RECT rect1={10,100,200,200};
 m_pListBox.Create(WS_CHILD | WS_VISIBLE | LBS_STANDARD,rect1,this,200);
 m_pListBox.ShowWindow(SW_SHOW);
 //데이터 삽입
 m_pListBox.AddString("data1");
 m_pListBox.AddString("data2");
 m_pListBox.AddString("data3");

 //에디터 박스 만들기
 RECT rect2={210,10,400,100};
 m_pEditBox.Create(
  WS_CHILD | WS_VISIBLE |
  ES_MULTILINE //여러 라인 입력
  | ES_AUTOHSCROLL | ES_AUTOVSCROLL| //자동 수직,수평 스크롤
  WS_BORDER |WS_VSCROLL,//외곽선과 수직 수크롤바 설정
    rect2,this,300);
 m_pEditBox.ShowWindow(SW_SHOW);

 //콤보박스 만들기
 RECT rect3={210,200,400,300};//콤보박스 출력 위치
 //윈도우 만들기
 m_pComboBox.Create(WS_CHILD | WS_VISIBLE|CBS_DROPDOWN ,rect3,this,400);
 m_pComboBox.ShowWindow(SW_SHOW);
 //콤보박스에 데이터를 넣는다.
 m_pComboBox.AddString("cdata1");
 m_pComboBox.AddString("cdata2");
 m_pComboBox.AddString("cdata3");


/*------KeyBoadData------------------------------------------------------------------*/

void CTESTView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 // TODO: Add your message handler code here and/or call default
 
 CString csText=_T("");

 csText=nChar;
 AfxMessageBox(csText);

 CFormView::OnChar(nChar, nRepCnt, nFlags);
}


/*------SendDlgItemMessage------------------------------------------------------------*/
 SendDlgItemMessage(IDC_STATIC_WLREM, WM_SETTEXT,0,(LPARAM)(LPSTR)"DATA NONE");

/*-------라디오버튼-------Radio button------------------------------------------------*/
//-------------------------------------------------------------------------------------

 tmModel.PCBType    = (rbSata.GetCheck()?0:1);
 tmModel.Rotate     = (rbRetn.GetCheck()?false:true);
 tmModel.ScrewCheck = (rbNChk.GetCheck()?false:true);
 tmModel.ScrewType  = (rbTyp1.GetCheck()?0:1);

 m_Select11.SetCheck(TRUE);
 m_Select11.SetCheck(FALSE);

 m_ccModeCheck3.SetWindowText("Photo(uA)");

 radio button
 변수 생성시 Gruop 지정

 0  : on
        -1 : off

 CNiPlot3D::PlotStyles style=m_Graph3D.GetPlots().Item(1).GetStyle();
 m_Point.SetCheck((style == CNiPlot3D::PlotStyles::Point)? 1 : 0);
 m_Line.SetCheck((style == CNiPlot3D::PlotStyles::Line)? 1 : 0);
 m_LinePoint.SetCheck((style == CNiPlot3D::PlotStyles::LinePoint)? 1 : 0);

/*------------List Box 변수 선언 대입------------------------------------------------*/
 
 CListBox  m_ListBox[4];

 m_ListBox[0].SubclassDlgItem(IDC_LIST1, this);
 m_ListBox[1].SubclassDlgItem(IDC_LIST2, this);
 m_ListBox[2].SubclassDlgItem(IDC_LIST3, this);
 m_ListBox[3].SubclassDlgItem(IDC_LIST4, this);

 m_ListBox[i].EnableWindow(FALSE);
 m_ListBox[port-1].AddString(m_strReceived[port-1]);
 m_ListBox[port-1].SetSel(m_ListBox[port-1].GetCount()-1, TRUE);

 m_ListBox[0].ResetContent();//clear


 m_ccModuleMeasureList.InsertString(nListNo,csFind);
//---List Control 빈문자 에러방지---------------------------------------------------
 if(m_ccName.GetCount()>0)
 {
   m_ccName.SetCurSel(m_nListCurrentNo);
   
    if(m_ccName.GetTextLen(m_ccName.GetCurSel())>0)
    {
    m_ccName.GetText(m_ccName.GetCurSel(),strTmp);
    m_csName=strTmp;
    }
    else
    {
    m_csName=_T("");
    }

   strTmp.Format("%d / %d", m_nListCurrentNo, m_nListMaxCount);
   SetDlgItemText(IDC_PAGEMODEL, strTmp);
   }
// m_ccModule_A_JobList.SetItemHeight(nListMaxCount,LISTHIGH2);//넓게 표시

/*----------------------------Check Box On/Off제어---------------------------------*/
 
 m_ccCheck.SetCheck(TRUE);//ON
 m_ccCheck.SetCheck(FALSE);//OFF

/*----------------------------------커서 활성-------------------------------------*/
 
 m_clbName.SetFocus();

/*----------------------------------콘트롤 보이기 숨기기--------------------------*/
 m_TestButton.ShowWindow(SW_HIDE);//(FALSE)
 m_TestButton.ShowWindow(SW_SHOW);//(TRUE)

/*------------콘트롤 생성--------------------------------------------------------*/
 public:
 CListBox m_pListBox;

 RECT rect={10,100,200,200};

 m_pListBox.Create(WS_CHILD|WS_VISIBLE|LBS_STANDARD,rect,this,200);
 m_pListBox.ShowWindow(SW_SHOW);
 m_pListBox.AddString("data1");
 m_pListBox.AddString("data2");
 m_pListBox.AddString("data3");

// m_ccName.GetText(m_ccName.GetCurSel(),strTmp);

/*------------콤보BOX Text제어--------------------------------------------------*/

 CString csTmp;
 int nNo=m_ccPalletSelect.GetCurSel();
 m_ccPalletSelect.GetLBText(nNo,csTmp);
 AfxMessageBox(csTmp);

 for(i=0; i<10; i++)
 {
 m_ccCombo.DeleteString(i);
 csText.Format("%dH:",i);
 m_ccCombo.InsertString(i,csText);
 }

/*------List Control-------------------------------------------------------------*/
 CString csTmp;
 m_ccNameList.AddString("DATA 1");

 m_ccNameList.SetCurSel(0);
 m_ccNameList.GetText(m_ccNameList.GetCurSel(),csTmp);


 if(m_cliItemName.GetTextLen(m_cliItemName.GetCurSel())>0)
 {
 m_cliItemName.GetText(m_cliItemName.GetCurSel(),csTmp);
 m_csItemName=csTmp;
 }
 
 for(i=m_ccName.GetCount()-1;i>=0;i--)
 {m_ccName.DeleteString(i);}

 if(m_cliItemName.GetCount()>0)
 {
  if(m_cliItemName.GetTextLen(m_nCurrentModelNo-1)>0)
  {
   m_cliItemName.GetText(m_nCurrentModelNo-1,strTmp);
  }

  SearchModelItemName(strTmp, false);
 }

/*--------------------Edit-> 리스트Box로 사용-----------------------------------*/
void CFOOLPROOFView::Status_display(CString sdisplay)
{
      //Edit -Control
 if ( m_ComDisplay.GetLineCount() > 5)
 {
  m_ComDisplay.SetSel(0, -1);
  m_ComDisplay.Clear();
 }
 
 sdisplay+="\r\n";
 m_ComDisplay.ReplaceSel(sdisplay);
 
/*--------------------Edit-> 커서 생성-----------------------------------------*/
 m_clbEdit.SetFocus();

}

//-------------Edit->GetWindowText----------------------------------------------------//
//-----------------------------------------------------------------------------------//
//--unsigned char-> CString ,  unsigned char-> char----------------------------------

 int Length= m_ccEdit1.GetWindowTextLength();
 unsigned char *temp = NULL;
 temp = new unsigned char [Length];

 char temp2[2]; CString csText;
 m_ccEdit1.GetWindowText((LPSTR)temp,255);

 for(int i=0; i<Length; i++)
 {
  temp2[0]=temp[i]; temp2[1]='\0';
  csText+=(LPSTR)temp2;
 }

 AfxMessageBox(csText);

//----------------------------------------------------
 char temp[255];
 for(int i=0; i<255; i++) temp[i]='\0';

 GetDlgItemText(IDC_EDIT1,(LPSTR)temp,255);
 GetDlgItemText(IDC_EDIT1,(char*)temp,255);
 CString csText=(LPSTR)temp;
 AfxMessageBox(csText);

//-----------------------------------------------------------------------------------//
/*-------------Control에 고유번호 부여 호출-----------------------------------*/
 CString Buf;
 CString data;
 CString BufSET;

 int No=1001; /*Resource.h -#define  IDC_EDIT  1001 */
 int No2=1004;

 data="A1입니다";
 SetDlgItemText(No,data);

 GetDlgItemText(No2,BufSET);
 AfxMessageBox(BufSET);

 UpdateData(FALSE);
/*----------------콘트롤에서 직접 text 얻기----------------------------------*/
 GetDlgItemText(IDC_SELECT_NAME_SCHOOL_YEAR1, csName);
 SetDlgItemText(IDC_PAGEMODEL, strText);


 //===========================================
 CString strRX, strRY;

 CStatic *pRX, *pRY;
 pRX = (CStatic *)GetDlgItem(IDC_LBL_RESULTX);
 pRY = (CStatic *)GetDlgItem(IDC_LBL_RESULTY);
 pRX->GetWindowText(strRX);
 pRY->GetWindowText(strRY);
/*------------------------FluxGrid 텍스트 중앙위치---------------------------*/
 m_GridData.SetCellAlignment(4);

/*-------------------StatusBar, 상태바---------------------------------------*/
void CMainFrame::DisplayMessage(CPoint point)
{
 CString msg;
 msg.Format("마우스 위치 : (%d, %d)",
  point.x, point.y);
 m_wndStatusBar.SetWindowText(msg);

 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 CRect rc;
        pFrame->m_wndStatusBar.GetItemRect (0, rc);

 pFrame->m_wndStatusBar.SetWindowText(csMsg);
}

/*-------------------ProgressBar----------------------------------------------*/

 // ProgressBar표시를 위한 부분
 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 pFrame->m_pProgressBar.SetRange(0, height-tHeight);
 pFrame->m_pProgressBar.SetStep(1);
 CRect rc;
        pFrame->pStatusBar->GetItemRect (0, rc);
 pFrame->m_pProgressBar.MoveWindow(&rc);

 pFrame->m_pProgressBar.StepIt();

//---------------------------------------------------------------------------*/


void CColorView::OnMouseMove(UINT nFlags, CPoint point)
{
 //#include "MainFrm.h"
 CMainFrame *pWnd = (CMainFrame*) AfxGetMainWnd();
 pWnd->DisplayMessage(point);
 CView::OnMouseMove(nFlags, point)
}

/*------------------------------SPIN Button 범위 지정--------------------*/

 1-12 까지 범위지정
void CDBdeleteDlg::OnDeltaposMonthStartSpin(NMHDR* pNMHDR, LRESULT* pResult)
{
 NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
 // TODO: Add your control notification handler code here
 UpdateData(TRUE);
 pNMUpDown->iPos = 0;
 m_MonthStartEdit -= (pNMUpDown->iDelta);
 if (m_MonthStartEdit<1)
 {
  m_MonthStartEdit = 1;
 }
 else if (m_MonthStartEdit>12)
 {
  m_MonthStartEdit = 1;
 }
 
 UpdateData(FALSE);

 *pResult = 0;
}
/*------------------------------콘트롤 화면 확장 --------------------*/

void CModel::ExpandyaContract()
{
 CRect rcDlg, rcMarker;
 GetWindowRect(rcDlg);
 
 if (!m_bExpanded)
 {
  m_nExpandedWidth = rcDlg.Width();
  m_Devide.GetWindowRect(rcMarker);
  m_nNormalWidth = (rcMarker.right - rcDlg.left);
  rcDlg.SetRect(rcDlg.left, rcDlg.top,    rcDlg.left + m_nNormalWidth+12,
   rcDlg.top + rcDlg.Height());
  HWND hWndChild = ::GetDlgItem(m_hWnd, IDC_STATIC_DEVIDE);
 
  while (hWndChild != NULL)
  { 
   hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT);
   ::EnableWindow(hWndChild, m_bExpanded);
  }
 }
 
 else
 {
  rcDlg.SetRect( rcDlg.left, rcDlg.top,    rcDlg.left + + m_nExpandedWidth,
   rcDlg.top + rcDlg.Height() );
  HWND hWndChild = ::GetDlgItem(m_hWnd, IDC_STATIC_DEVIDE);
 
  while (hWndChild != NULL)
  { 
   hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT);
   ::EnableWindow(hWndChild, m_bExpanded);
  }
 
 }
 
 MoveWindow(rcDlg, TRUE);
 
 m_bExpanded = !m_bExpanded;


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// -    HDC 얻기    -  ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

 CMainFrame *pFrame= (CMainFrame*)AfxGetMainWnd();ASSERT(pFrame);
 pFrame->m_flagTemplate = TRUE;
 

 CRect rect;rect.left=0;rect.right=100;rect.top=0;rect.bottom=200;

 CDC *pDC; pDC = GetDC();
 DrawRect(pDC, rect, RGB(0,0,255), 2);


 CClientDC pDC(this);
 DrawRect(&pDC, rect, RGB(0,0,255), 2);


 HWND hParent = ::GetParent(m_hWnd);


 CMainFrame* pWnd = (CMainFrame*)AfxGetApp()->m_pMainWnd;
 HDC hDC = GetDC(pWnd->m_hWnd);

 CDC *pDC; pDC = GetDC();
 EraseBkgnd(pDC,m_CamRect,m_DisRect);


 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 CDC *pDC =pFrame->GetDC();

 StretchDIBits(pDC->GetSafeHdc(),20,20,width,height,
 0, 0,width, height, m_ColorGetImg, (LPBITMAPINFO)&dibHi, DIB_RGB_COLORS, SRCCOPY);


 CPaintDC dc(this); // device context for painting
 int width=m_CamRect.right; int height=m_CamRect.bottom;
 // TODO: Add your message handler code here
 CPaintDC dcView(GetDlgItem(IDC_IMG_HISTO_VIEW));
 
 CRect rect;
 GetDlgItem(IDC_IMG_HISTO_VIEW)->GetClientRect(&rect);
 StretchDIBits(dcView.m_hDC,rect.left,rect.top,rect.right,rect.bottom, 0, 0,
  width, height, m_pTestBitmap, &m_pBitmapInfo, BI_RGB, SRCCOPY);

 CRect rect;
 GetDlgItem(IDC_IMG_HISTO_VIEW)->GetWindowRect(&rect);
 ScreenToClient(rect);
 InvalidateRect(&rect, FALSE);


 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 //CChildFrame *pFrame = (CChildFrame *)AfxGetMainWnd();

// CPaintDC *pDC;
 CDC *pDC =pFrame->GetDC();

 CVisionSysView* pView =( CVisionSysView* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();
 CVisionSysDoc *pDoc=pView->GetDocument();
 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
// CDC *pDC =pFrame->GetDC();
 CDC *pDC =pView->GetDC();

/*-------------- HDC 얻기------------------------------------------------------------*/

CWnd *pWnd = GetDlgItem(IDC_CAMERA_VIEW);


void CGraphResultPage3::DrawBitmap()
{
 if (m_buf==NULL) return;

 CRect rect;
 GetDlgItem(IDC_IMG_HISTO_VIEW)->GetWindowRect(&rect);
 ScreenToClient(rect);
 InvalidateRect(&rect, FALSE);
}

void CGraphResultPage3::OnPaint()
{
 CPaintDC dc(this); // device context for painting
 
 // TODO: Add your message handler code here
 if (m_buf==NULL) return;

 BYTE *tmp;
 // DWORD-align for display
 tmp = JpegFile::MakeDwordAlignedBuf(m_buf,m_width,m_height,&m_widthDW);
 // set up a DIB
 BITMAPINFOHEADER bmiHeader;
 bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
 bmiHeader.biWidth = m_width;  bmiHeader.biHeight = m_height;
 bmiHeader.biPlanes = 1;    bmiHeader.biBitCount = 24;bmiHeader.biCompression = BI_RGB;
 bmiHeader.biSizeImage = 0;   bmiHeader.biXPelsPerMeter = 0;
 bmiHeader.biYPelsPerMeter = 0;bmiHeader.biClrUsed = 0;
 bmiHeader.biClrImportant = 0;// CRect rect;

 int width=bmiHeader.biWidth; int height=bmiHeader.biHeight;
 
 CPaintDC dcView(GetDlgItem(IDC_IMG_HISTO_VIEW));
 dcView.SetStretchBltMode(STRETCH_DELETESCANS);

 CRect rect;
 GetDlgItem(IDC_IMG_HISTO_VIEW)->GetClientRect(&rect);
 StretchDIBits(dcView.m_hDC,rect.left,rect.top,rect.right,rect.bottom,
  0, 0,width, height, tmp, (LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS, SRCCOPY);
 delete [] tmp;
 // Do not call CPropertyPage::OnPaint() for painting messages
}

/*-------------- HDC 얻기------------------------------------------------------------*/
 CDC *theDC = GetDC();

 if (theDC!=NULL) {

  CRect clientRect;
  GetClientRect(clientRect);

  // Center It
  UINT left = (clientRect.Width() - m_width) / 2;
  UINT top = (clientRect.Height() - m_height) / 2;

  // a 24-bit DIB is DWORD-aligned, vertically flipped and
  // has Red and Blue bytes swapped. we already did the
  // RGB->BGR and the flip when we read the images, now do
  // the DWORD-align

  BYTE *tmp;
  // DWORD-align for display
  tmp = JpegFile::MakeDwordAlignedBuf(m_buf,
           m_width,
           m_height,
           &m_widthDW);
  // set up a DIB
  BITMAPINFOHEADER bmiHeader;
  bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
  bmiHeader.biWidth = m_width;
  bmiHeader.biHeight = m_height;  bmiHeader.biPlanes = 1;
  bmiHeader.biBitCount = 24;
  bmiHeader.biCompression = BI_RGB;
  bmiHeader.biSizeImage = 0;
  bmiHeader.biXPelsPerMeter = 0;
  bmiHeader.biYPelsPerMeter = 0;
  bmiHeader.biClrUsed = 0;
  bmiHeader.biClrImportant = 0;

  //---------------------------------------------
   theDC->SetStretchBltMode(STRETCH_DELETESCANS);
  //---------------------------------------------
  // now blast it to the CDC passed in.
  // lines returns the number of lines actually displayed

  int lines = StretchDIBits(theDC->m_hDC,
         BMP_START_EDGE_X1,BMP_START_EDGE_Y1,
         512,
         384,
         0,0,
         bmiHeader.biWidth,
         bmiHeader.biHeight,
         tmp,
         (LPBITMAPINFO)&bmiHeader,
         DIB_RGB_COLORS,
         SRCCOPY);

  delete [] tmp;

  CString info;
  info.Format("(%d x %d)", m_width, m_height);
  theDC->SetBkMode(TRANSPARENT);
  theDC->SetTextColor(RGB(0,0,0));
  theDC->TextOut(10,5, info);
 
  ReleaseDC(dc);

/*-------------- 다일로그/Propet 꽉찬 화면출력 화면-----------------------------------------*/

int CSETDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
 if (CDialog::OnCreate(lpCreateStruct) == -1)
  return -1;
 
 // TODO: Add your specialized creation code here
  ShowWindow(SW_SHOWMAXIMIZED);///화면  확대
  UpdateWindow();           
 return 0;
}

/*-------------- Dialog를 메인화면으로 사용-----------------------------------------*/

 #include "commtestDlg.h"

BOOL CCommtestApp::InitInstance()
{
 // Standard initialization
 // If you are not using these features and wish to reduce the size
 //  of your final executable, you should remove from the following
 //  the specific initialization routines you do not need.

 #ifdef _AFXDLL
 Enable3dControls();   // Call this when using MFC in a shared DLL
 #else
 Enable3dControlsStatic(); // Call this when linking to MFC statically
 #endif

 CCommtestDlg dlg;
 m_pMainWnd = &dlg;
 dlg.DoModal();

 // Since the dialog has been closed, return FALSE so that we exit the
 //  application, rather than start the application's message pump.
 return FALSE;
}
/*----------------------------------------------------------------------------------*/
 MainFrame *pFrame=(CMainFrame*)AfxGetMainWnd();
 CChildFrame *pChild=(CChildFrame*)pFrame->GetActiveFrame();
 CWinColorDoc *pDoc=(CWinColorDoc*)pChild->GetActiveDocument();
 CWinColorView *pView=(CWinColorView*)pChild->GetActiveView();
/*-------------- View 에서 App 얻기------------------------------------------------*/

 CSECKLineDVM2App* pApp = (CSECKLineDVM2App*)AfxGetApp();
 pApp->SetSerialInfo();


/*-------------- Doc 에서 View 얻기------------------------------------------------*/
 CServerNetWorkView *pView=(CServerNetWorkView *)((CMainFrame *)AfxGetMainWnd())->GetActiveView ();
 pView->Status_display(lpszMessage);


/*-------------- View에서  Doc 얻기------------------------------------------------*/
 CSECKLineDVM2Doc* pDoc = GetDocument();
 
 pDoc->
/*--------------메인프레임에서 View, Doc 얻기-------------------------------------*/
 CSECKLineDVM2View* pView =
 (CSECKLineDVM2View* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();

 pView->
 
 CCSECKLineDVM2MultiDoc *pDoc;
 pDoc=pView->GetDocument();

 pDoc->

/*--------------다일로그에서  View, MainFrame, Doc 얻기---------------------------*/
        ..Dlg.h화일에 참조선언
        #include "SECKLineDVM2MultiDoc.h"

        ..Dlg.cpp화일에 참조선언
        #include "CSECKLineDVM2MultiView.h"
        #include "MainFrm.h"

 CSECKLineDVM2MultiView *pView=(CSECKLineDVM2MultiView *)((CMainFrame *)AfxGetMainWnd())->GetActiveView ();
 pView->

 CMainFrame* pFrame;
 pFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd;
 
 pFrame->

 CSECKLineDVM2View* pView =( CSECKLineDVM2View* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();
 CSECKLineDVM2Doc *pDoc;
 pDoc=pView->GetDocument();

 pDoc->

/*----------------------------다일로그 호출 종료----------------------------------*/
 CProgressDlg Dlg;
 Dlg.Create();
 Dlg.DestroyWindow();

 //--------------
 EndDialog(IDOK);
 CDialog::OnCancel();
 EndDialog(IDCANCEL);
 //--------------

/*------------------------MessageBox 선택-----------------------------------------*/
 if (AfxMessageBox("모델코드를 찾지 못했습니다.!\n모델을 입력 하시겠습니까?.", MB_YESNO) == IDYES)
 {
 }
 else
 {
 return;
 }

/*-------------화면갱신----------------------------------------------------------*/

 Invalidate(TRUE);
 RedrawWindow();

/*-------------------------------------------------------------------------------*/

/*------------타이틀 제목 없애기-------------------------------------------------*/
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
 if( !CFrameWnd::PreCreateWindow(cs) )
  return FALSE;
 // TODO: Modify the Window class or styles here by modifying
 //  the CREATESTRUCT cs
 cs.style^=FWS_ADDTOTITLE; //제목 없음 없에기
 return TRUE;

 cs.style = WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX | WS_MAXIMIZE;
 cs.lpszName = " WASS-2000 Scanning System";
 cs.x = cs.y = 0;
 cs.cx = rct.right;
 cs.cy = rct.bottom;

}

/*----------------------전체 화면 출력 위치조정------------------------------*/
 cs.x=200; cs.y=200; cs.cx=400; cs.cy=400;

/*----------------------다일로그 디스플레이 위치 변경------------------------*/
CExpansionDlg1* g_pExpansion = NULL;

 if(!g_pExpansion)
 {
    g_pExpansion = new CExpansionDlg1(this);
    g_pExpansion->MoveWindow(50,387,354,320,true);//x,y,with,high
    Invalidate(TRUE);
 }

/*------------------프로그램 종료--------------------------------------------*/
 윈도우 "x" 종료 (도큐먼트에 설정)


void CMainFrame::OnClose()
{
 // TODO: Add your message handler code here and/or call default
 
 if (MessageBox("프로그램을 종료 하시겠습니까? ", " 재고관리프로그램",
  /*MB_ICONQUESTION*/ MB_ICONSTOP | MB_OKCANCEL) == IDOK)  {
  PostQuitMessage(0);
  CFrameWnd::OnClose();
 }
}

BOOL CScrubDoc::SaveModified()
{
 // TODO: Add your specialized code here and/or call the base class
 if(AfxMessageBox("프로그램을 종료하시겠습니까?",MB_ICONQUESTION|MB_YESNO)==IDYES)
 {
 OnClose();
 PostQuitMessage(0);
 //((CMainFrame*)AfxGetApp()->m_pMainWnd)->SendMessage(WM_CLOSE,0,0);

 }
 else
 {
  return 0;
 }

/* CMainFrame* m_pMainWnd;
 CMainWidowCloseDoc* pDataDoc = GetDocument();
 
 if(IDOK==AfxMessageBox("프로그램을 종료하시겠습니까?",MB_OKCANCEL))
 
 m_pMainWnd->OnClose;
 pDataDoc->OnCloseDocument();
*/ return CDocument::SaveModified();
}
{
 if(AfxMessageBox("프로그램을 종료하시겠습니까?",MB_ICONQUESTION|MB_YESNO)==IDYES)
 {
 OnClose();
 PostQuitMessage(0);
 }
 else
 {
  return;
 }
}

/*--------------------프로그램 종료-------------------------------------------*/
 ::ExitProcess(-1);

/*--------------------프린트다일로그 않보이고 바로 출력하기-------------------*/
BOOL CManagementView::OnPreparePrinting(CPrintInfo* pInfo)
{
 // default preparation
 pInfo->m_bDirect=TRUE;
 return DoPreparePrinting(pInfo);
}
/*---------------------------다일로그 호출-----------------------------------*/
 CMyGraphDemoDlg dlg;
 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with OK
 }
 else if (nResponse == IDCANCEL)
 {
  // TODO: Place code here to handle when the dialog is
  //  dismissed with Cancel
 }

/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - Windows 제 어  -  ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------*/
/*-------------- 다일로그 크기조절            ---------------------------------------*/
/*-----------------------------------------------------------------------------------*/

 SetWindowText("Image View");
 MoveWindow(50, 50,400,300); //x위치, y위치, x Size, y Size

/*-----------------------------------------------------------------------------------*/
/*-------------- 윈도우 항상 위에 활성        ---------------------------------------*/
/*-----------------------------------------------------------------------------------*/
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
 cs.dwExStyle = WS_EX_TOPMOST;
}


/*-----------------------------------------------------------------------------------*/
/*-------------- Menu Bar를 지우기            ---------------------------------------*/
/*-----------------------------------------------------------------------------------*/
 
 CMenu* pMenu = new CMenu;
 pMenu->Attach(cs.hMenu);
 pMenu->DestroyMenu();
 cs.hMenu = NULL;
 delete pMenu;
 
/*-----------------------------------------------------------------------------------*/
/*-------------- 화면 갱신                    ---------------------------------------*/
/*-----------------------------------------------------------------------------------*/

 CStatic m_PcbImageView;
 CRect  m_rectLargeCanvas;

 m_PcbImageView.GetWindowRect(&m_rectLargeCanvas);
 ScreenToClient(&m_rectLargeCanvas);
 InvalidateRect(m_rectLargeCanvas,FALSE);
 //===============================================

 Invalidate(TRUE);Invalidate(false);
 RedrawWindow();
 UpdateAllViews(FALSE);
        UpdateData(FALSE);

/*------Hot Key------------------------------------------------------------*/
//--------------------------------------------------------------------------
BOOL CBroadView::PreTranslateMessage(MSG* pMsg)
{
 // TODO: Add your specialized code here and/or call the base class
 if (pMsg->message==MM_MCINOTIFY) {
  if (pMsg->wParam==MCI_NOTIFY_SUCCESSFUL) {
   StopWav();
  }
 }
 if (pMsg->message==MY_MSG_FIRE_OFF) {
  FireOff();
 }
 if (pMsg->message==WM_KEYDOWN) {
  if (GetAsyncKeyState(VK_F1)&0x8000) {
   if (GetAsyncKeyState(VK_F5)&0x8000) {
    if (GetAsyncKeyState(VK_F9)&0x8000) {
     if (m_SetupBtn.IsWindowVisible()==FALSE) {
      FuncBtnShow(SW_SHOW);
     }
    }
   }
  }

  // 2007.2.15
  if (GetAsyncKeyState(VK_F6)&0x8000){m_bPingViewChk=TRUE;Invalidate(FALSE);SetTimer(REDRAW_TIMER,2000,NULL);}//RedrawWindow();

 }

 return CFormView::PreTranslateMessage(pMsg);
}
/*-------------- 메인프레임 상속 받아 다일로그 호출-----------------------------------------*/
//--------------------------------------------------------------------------------------------
void ResultShowDlgBar(CString str)
{
 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 CRect rect;
 pFrame->GetWindowRect(&rect);

 if (!pFrame->m_ResultShowBar.IsWindowVisible())
 {
  pFrame->DockControlBar(&pFrame->m_ResultShowBar);
  pFrame->m_ResultShowBar.ShowWindow(SW_SHOW);
  pFrame->FloatControlBar(&pFrame->m_ResultShowBar,CPoint(rect.right-324,rect.bottom-125));
 }


 CEdit *pEdit = (CEdit *)pFrame->m_ResultShowBar.GetDlgItem(IDC_RESULTSHOW);
 int nLength = pEdit->GetWindowTextLength();
 
 if(nLength<10000) pEdit->SetSel(nLength, nLength);
 else pEdit->SetSel(nLength-10000, nLength);
 pEdit->ReplaceSel(str);
 pFrame->RecalcLayout();

}

/*-----------------------------------------------------------------------------------*/
/*-------------- Extern File에서 다일로그제어 ---------------------------------------*/
/*-----------------------------------------------------------------------------------*/
#include "TestDlg.h"
CTestDlg *TestDlg;
TestDlg=NULL;

 if(TestDlg->GetSafeHwnd() == NULL)
 {
  TestDlg= new CTestDlg;
  TestDlg->Create(IDD_TESTDIALOG1);
  //manu_Swstatus = MENU_MANUAL;//3
 }
 TestDlg->ShowWindow(FALSE);
// TestDlg->SetDlgItemText(IDC_DLGSTATIC,"TEST 2006.12");
 TestDlg->m_csData="Dlg Text 2006";

 if(TestDlg->GetSafeHwnd() != NULL) TestDlg->ShowWindow(true);


 if(TestDlg->GetSafeHwnd() != NULL)
 {
  CString csTmp;
  TestDlg->GetDlgItemText(IDC_DLGSTATIC,csTmp);
  AfxMessageBox(csTmp);
 }

 //============================================================
 void ResultShowDlgBar(CString str)
 {
 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd();
 CRect rect;
 pFrame->GetWindowRect(&rect);

 if (!pFrame->m_ResultShowBar.IsWindowVisible())
 {
  pFrame->DockControlBar(&pFrame->m_ResultShowBar);
  pFrame->m_ResultShowBar.ShowWindow(SW_SHOW);
  pFrame->FloatControlBar(&pFrame->m_ResultShowBar,CPoint(rect.right-324,rect.bottom-125));
 }


 CEdit *pEdit = (CEdit *)pFrame->m_ResultShowBar.GetDlgItem(IDC_RESULTSHOW);
 int nLength = pEdit->GetWindowTextLength();
 
 if(nLength<10000) pEdit->SetSel(nLength, nLength);
 else pEdit->SetSel(nLength-10000, nLength);
 pEdit->ReplaceSel(str);
 pFrame->RecalcLayout();
}
/*-----------------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------------*/
/*-------------- 다일로그 확장-------------------------------------------------------*/

 int m_nNormalWidth;
 int m_nExpandedWidth;
 BOOL m_bExpanded;

   void  CExpandDlgDlg::ExpandyaContract()
   {
 CRect rcDlg, rcMarker;
 GetWindowRect(rcDlg);
 
 if (!m_bExpanded)
 {
  m_nExpandedWidth = rcDlg.Width();
  m_Devide.GetWindowRect(rcMarker);
  m_nNormalWidth = (rcMarker.right - rcDlg.left);
  rcDlg.SetRect(rcDlg.left, rcDlg.top,    rcDlg.left + m_nNormalWidth+12,
   rcDlg.top + rcDlg.Height());
  HWND hWndChild = ::GetDlgItem(m_hWnd, IDC_STATIC_DEVIDE);
 
  while (hWndChild != NULL)
  { 
   hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT);
   ::EnableWindow(hWndChild, m_bExpanded);
  }

 }
 
 else
 {
  rcDlg.SetRect( rcDlg.left, rcDlg.top,    rcDlg.left + + m_nExpandedWidth,
   rcDlg.top + rcDlg.Height() );
  HWND hWndChild = ::GetDlgItem(m_hWnd, IDC_STATIC_DEVIDE);
 
  while (hWndChild != NULL)
  { 
   hWndChild = ::GetNextWindow(hWndChild, GW_HWNDNEXT);
   ::EnableWindow(hWndChild, m_bExpanded);
  }
 
 }
 
 MoveWindow(rcDlg, TRUE);
 
 m_bExpanded = !m_bExpanded;
 

  }

/*-----------------------------------------------------------------------------------*/
/*-------------- 투명 다일로그-------------------------------------------------------*/
#define WS_EX_LAYERED 0x00080000
#define LWA_COLORKEY 1 // Use color as the transparency color.
#define LWA_ALPHA    2 // Use bAlpha to determine the opacity of the layer

typedef BOOL (WINAPI *lpfn) (HWND hWnd, COLORREF cr, BYTE bAlpha, DWORD dwFlags);
lpfn g_pSetLayeredWindowAttributes;


 HMODULE hUser32 = GetModuleHandle(_T("USER32.DLL"));
     g_pSetLayeredWindowAttributes = (lpfn)GetProcAddress(hUser32, "SetLayeredWindowAttributes");
    HWND m_hCurrWnd;    //  Handle to the window over which the mouse was last present
 m_hCurrWnd=*this;
    if  (g_pSetLayeredWindowAttributes)
    {
          ::SetWindowLong(m_hCurrWnd, GWL_EXSTYLE, GetWindowLong(m_hCurrWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
          g_pSetLayeredWindowAttributes(m_hCurrWnd, 50, 100, LWA_ALPHA);
 }
/*-----------------------------------------------------------------------------------*/
/*-------------- Windows 이벤트------------------------------------------------------*/
        #define define WSA_ASYNC    (WM_USER+1)
 //.h-----------------------------------
 protected:
   //{{AFX_MSG(CHDDINSPView)
   afx_msg LONG UDPOnReceive(UINT,LONG);

 //.cpp----------------------------------
 BEGIN_MESSAGE_MAP(CHDDINSPView, CFormView)
  //{{AFX_MSG_MAP(CHDDINSPView)
   //}}AFX_MSG_MAP
  ON_MESSAGE(WSA_ASYNC,UDPOnReceive)

 LONG CHDDINSPView::UDPOnReceive(UINT wParam, LONG lParam)
 {
 }

/*-----------------------------------------------------------------------------------*/
/*-------------- 스레드에서 변수 참조------------------------------------------------*/

UINT RepeatThread(LPVOID pFuncData)
{
 CCAMCFS20Dlg *pParent = (CCAMCFS20Dlg *)pFuncData;
 INT16 nAxis;
 double dDistance, dVelocity, dAccel;

 nAxis  = pParent->m_nAxis;
 dDistance = pParent->GetDlgItemDouble(IDC_DISTANCE);
 dVelocity = pParent->GetDlgItemDouble(IDC_VELOCITY);
 dAccel  = pParent->GetDlgItemDouble(IDC_ACCELERATION);
 pParent->bRepeatFlag = TRUE;
}

void CWinColorView::OnDraw(CDC* pDC)
{
 CWinColorDoc* pDoc = GetDocument();
 ASSERT_VALID(pDoc);

 // TODO: add draw code for native data here
 if(pDoc->m_InImg==NULL) return;

 height = pDoc->dibHi.biHeight;
 width = pDoc->dibHi.biWidth;
 rwsize = WIDTHBYTES(pDoc->dibHi.biBitCount*pDoc->dibHi.biWidth);
 BmInfo->bmiHeader = pDoc->dibHi;

 SetDIBitsToDevice(pDC->GetSafeHdc(),0,0,width,height,
      0,0,0,height,pDoc->m_InImg,BmInfo, DIB_RGB_COLORS);
}

/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// -    기타 정리    -  ///////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

//------프로그램 폴더안에 include화일 참조 선언 -----------------------------------------//
#include "../include/PortInclude.h"

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


//---시간 계산---------------------------------------------------------------------------//
double m_lStartTimeOneChipCycle = GetCurrentTime();
double m_lEndTimeOneChipCycle = GetCurrentTime();
double m_OneCycleTime=(m_lEndTimeOneChipCycle - m_lStartTimeOneChipCycle) * 0.001;
//---------------------------------------------------------------------------------------//

/*----------------------------------시간 얻기-------------------------------------*/
 COleDateTime ccTestTime;
 CString strTmp;

 ccTestTime=COleDateTime::GetCurrentTime();
// strTmp=ccTestTime.Format("%I:%M:%S %p");
 strTmp=ccTestTime.Format("%I:%M:%S");
 m_clbTime.SetCaption(strTmp);

 int nTime;
 COleDateTime odtDate=COleDateTime::GetCurrentTime();
 nTime=odtDate.GetYear();
 nTime=odtDate.GetMonth();
 nTime=odtDate.GetDay();
 nTime=odtDate.GetHour();
 nTime=odtDate.GetMinute();
 nTime=odtDate.GetSecond();


 SYSTEMTIME SystemTime, SystemTime2;
 GetSystemTime( &SystemTime);

 GetSystemTime( &SystemTime2);
 TRACE("JOG MINUS Time Value = %d \n", SystemTime2.wMilliseconds - SystemTime.wMilliseconds);
//---------------------------------------------------------------------------------------//

/* 선언부 */
#define  PI  3.1415926535
#include <math.h>
#define   RADIUS  150  

// 1. 영역구함

CRect rect;
GetClientRect(rect);

// 2. 이미지 중간점 구함

int  m_nCenterX       = rect.Width() / 2;  // Center X point
int  m_nCenterY       = rect.Height()/ 2;  // Center Y point

// 3. 반지름

int  nHalf      = RADIUS; // 반지름

// 4. 계산할 각도 구함

int  m_nAngle = 0;
m_nAngle = 360 / m_nRingNum;  //  m_nRingNum <-- 점의 갯

// 5. 저장할 점 선언

CPoint  *pt;
for ( int i = 0; i < m_nRingNum ; i++)

{
    int nAxisX = 0;
    int nAxisY = 0;

    if( i == 0)
    {
        nAxisX      = (int)(    cos(360*(PI / 180)) * nHalf );          // X point
        nAxisY      = (int)(    sin(360*(PI / 180)) * nHalf );          // Y point
    }
    else

    {  
        nAxisX      = (int)(    cos((m_nAngle*i)*(PI / 180)) * nHalf    );      // X point
        nAxisY      = (int)(    sin((m_nAngle*i)*(PI / 180)) * nHalf    );      // Y point
    }
    // 6. 구한 점 저장

    pt[i].x = nAxisX;
    pt[i].y = nAxisY
}


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 다른프로그램 실행 -  /////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/


/*------인터넷사이트 실행------------------------------------------------------------*/
 WinExec("C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE www.taeyang.com",SW_SHOW);

 WinExec("C:\\YeTools\\CpComSys\\CpPrc.exe",SW_SHOWMINIMIZED);

/*------응용프로그램 실행------------------------------------------------------------*/
 h. 헤더파일 선언 PROCESS_INFORMATION m_pi; //다른 프로그램 자동 실행및 종료를 위한
 

 STARTUPINFO StartupInfo = {0};
 StartupInfo.cb = sizeof(STARTUPINFO);
 PROCESS_INFORMATION ProcessInfo;
 
 StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
 StartupInfo.wShowWindow = SW_HIDE;//안보이기 SW_SHOWMINIMIZED-최소화
 
 if(!::CreateProcess(NULL, "C:\\YeTools\\CpComSys\\DLL\\CpPrc.exe",
        //if(!::CreateProcess(NULL, "DataCPK.exe",
 NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo, &ProcessInfo))
 {
 AfxMessageBox("C:\\YeTools\\CpComSys\\CpPrc.exe 실행 화일을 찾을 수 없습니다.");
 }
 m_pi = ProcessInfo;


 // 종료------Close------------------------
 HANDLE Killprocess;
 CString szKillProgramName;
 szKillProgramName = "C:\\YeTools\\CpComSys\\CpPrc.exe";//종료할 프로그램 위칭르 넣으 시요..
     Killprocess = OpenProcess(PROCESS_TERMINATE,0,m_pi.dwProcessId);
     TerminateProcess(Killprocess, (unsigned)-1);

C:\\Program Files\\Amfis1130\\SigmaTV.exe
/*
 CloseHandle(m_pi.hProcess);
 CloseHandle(m_pi.hThread);
 LPSTR    gAppName = "C:\\YeTools\\CpComSys\\CpPrc.exe";
 if (FindWindow(gAppName, NULL)) {
     PostQuitMessage(0);
 }
*/

/*------NOTE PAD 실행------------------------------------------------------------*/
 char csNote[128];
 strcpy(csNote,"c:\\Windows\\NOTEPAD ");
 strcat(csNote,filename);
 WinExec(csNote,SW_SHOW);


//------CString에 저장 후 메모장으로 보기------------------------------------------
m_csDisplay="";m_bShowDisplay=true;
NotePadDisplay();

void Status_display(CString sdisplay)
{
 if(m_bShowDisplay){m_csDisplay+=sdisplay+"\n";  if(m_csDisplay.GetLength()>=65550)m_csDisplay=""; }
}
void    NotePadDisplay(void)
{
 FILE *fp; CString Contents, datename, filename;
 filename="test.txt";
 if ((fp = fopen(filename,"w+")) == NULL) {
  AfxMessageBox("File Open Error.");  
  fclose(fp);
  return ;}

 Contents.Insert(Contents.GetLength(),m_csDisplay);
 fwrite(Contents,1,Contents.GetLength(),fp);
 fclose(fp);

 char csNote[128];
 strcpy(csNote,"c:\\Windows\\NOTEPAD ");
 strcat(csNote,filename);
 WinExec(csNote,SW_SHOW);

 strcpy(csNote,"c:\\WINNT\\NOTEPAD ");
 strcat(csNote,filename);
 WinExec(csNote,SW_SHOW);
}

/*------실행화일 디렉토리 구하기--- -------------------------------------------------------*/
//--------SetCurrentDirectory----------------------------------------------------------------
 if( mDAT.tot < 1 )       return;
 int  stat;
 char *str;
 CString  fname;
 DATE_INF day;
 str = new char[MAX_PATH+10];
 ::GetCurrentDirectory(MAX_PATH+1,str);
 uiGetSysDate(&day);
 fname.Format(_T("DOC\\%s%04d%02d%02d.TXT"),
 //-----------------------------------------------------------
 (char *)(LPCTSTR)mDAT.pid,day.yy%100,day.mo,day.dd);
 //-----------------------------------------------------------
 CFileDialog  dlg(FALSE,"DOC",fname,OFN_HIDEREADONLY,"프린트화일 (*.TXT)|*.TXT");
 stat = dlg.DoModal();
 ::SetCurrentDirectory(str);
 delete str;
 if( stat != IDOK )       return;
 fname = dlg.GetPathName();     ApSaveSeekDataInfor(fname,mDAT);


 char *str;
 CString  fname;
 str = new char[_MAX_PATH+1];
 ::GetCurrentDirectory(_MAX_PATH+1,str);

 AfxMessageBox((LPCTSTR)(char *)str);


//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 화 일 -  /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

//======================================================================================
/*------파일 다일로그-----------------------------------------------------------------*/
//======================================================================================

//==============화일 다일로그 PATH 지정 sprintf (CString으로 지정이 않되는 경우)=============

   CString csModelFile="C:\\AttachMachine\\Model\\MODEL1.txt";
   char szBuf[1024];sprintf(szBuf,csModelFile);


//===============화일 Load 다일로그==========================================================
void CAttachMachineView::OnClickFileLoadBtn()
{
 // TODO: Add your control notification handler code here
        CFileDialog filedlg( TRUE,// TRUE : FileOpen, FALSE :FileClose
 _T("ini"),   // 디폴트 확장자
 //_T("C:\\AttachMachine\\EquipSys\\*.*"),  // 디폴트 파일명 --마지막\\*.*
        _T("C:\\AttachMachine\\EquipSys\\Test.ini"),  // 디폴트 파일명 --현재 사용 파일을 제시
 OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST| OFN_SHOWHELP,
 // OPENFILENAME
 // OFN_CREATEPROMPT
 //"텍스트 파일 (*.txt) | *.txt |데이타 파일 (*.dat; *.hex) | *.dat; *.hex|모든 파일 (*.*) | *.* ||",
 "File Load Data INI Files (*.ini)|*.ini||",
 // 필터
 // 부모 윈도우
 NULL
 );

 if(filedlg.DoModal()==IDOK)
 {
  CString szFileDir=filedlg.GetPathName(); 
  SEQ.csSpecFileName=szFileDir;
  FileData_DataSysGet(szFileDir,FILE_SPEC);
  Sub_SpecDataDisplay();
 }
}

//================새로운 이름으로 저장  =====================================================
void CAttachMachineView::OnClickFileNewSaveBtn()
{
 // TODO: Add your control notification handler code here
 CString szFileName=""; CString csFileName="";
 CString szFileDir="";
 CString csTmp="";  CString csCh=""; CString csLoad="";
 //CFileDialog filedlg(FALSE,_T(""),_T(csTmp),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,//저장
 //CFileDialog filedlg(FALSE,_T(""),_T("C:\\AttachMachine\\Model\\*.*"),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,//저장  
        CFileDialog filedlg(FALSE,_T(""),_T("C:\\AttachMachine\\Model \\Test.ini"),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,//저장,현재 사용 파일을 제시
 
  "Save AS Data INI Files (*.ini)|*.ini||",NULL);//"files (*.*)",NULL);
 if (filedlg.DoModal()==IDOK)
 {
 szFileDir=filedlg.GetPathName();   //AfxMessageBox(szFileDir);//전체 화일+확장자까지
 if(Sub_SpecDataFileSave(szFileDir))
 {
  SEQ.csSpecFileName=szFileDir;
 }
 else
  AfxMessageBox("화일로 저장 하지 못했습니다.");
 }
}


/*------파일열기 다일로그------------------------------------------------------------*/
      void CFileDlgDlg::OnOpenFile()
      {
 // TODO: Add your control notification handler code here
 CFileDialog dialog( TRUE,// TRUE : FileOpen, FALSE :FileClose
 _T("txt"),   // 디폴트 확장자
 _T("C:\\Data\\*.*"),  // 디폴트 파일명 --마지막\\*.*
 OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST| OFN_SHOWHELP,
 // OPENFILENAME
 // OFN_CREATEPROMPT
 "텍스트 파일 (*.txt) | *.txt |데이타 파일 (*.dat; *.hex) | *.dat; *.hex|모든 파일 (*.*) | *.* ||",
 // 필터
 // 부모 윈도우
 NULL
 );

 dialog.DoModal();
     }

 //---------------------------------------------------------------
 CString InitialDir=Path_Image;// AfxMessageBox(Path_Model);
 InitialDir+="*.*";

 CString Title      = "SET IMAGE LOAD";
 //-------------------
 LPSTR File = InitialDir.GetBuffer(InitialDir.GetLength()*2);  //*char

 CFileDialog ImgDlg(TRUE,_T(Title),_T(InitialDir),OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST| OFN_SHOWHELP,  
// CFileDialog ImgDlg(TRUE,_T(Title),File,OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST| OFN_SHOWHELP,  
  "Image files (*.jpg)|*.jpg||",NULL);

 if (ImgDlg.DoModal()==IDOK)
 {
     //   tmModel.SetImage = ExtractFileName(ImgDlg->FileName);
     //   dpSname->CaptionFalse = tmModel.SetImage;
     }
 //---------------------------------------------------------------

      void CFileDlgDlg::OnSaveFile()
      {
 // TODO: Add your control notification handler code here
        CFileDialog dialog( FALSE,// TRUE : FileOpen,// FALSE :FileClose
                _T("txt"),   // 디폴트 확장자
                    _T("C:\\Data\\Untitled.txt"), // 디폴트 파일명
       OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
    // OPENFILENAME
    // OFN_CREATEPROMPT
      "텍스트 파일 (*.txt) | *.txt |데이타 파일 (*.dat; *.hex) | *.dat; *.hex|모든 파일 (*.*) | *.* ||",
   // 필터
   // 부모 윈도우
                    NULL
   );
 dialog.DoModal();
    }
 //===파일 읽기/저장 다일로그 ========================================================

 CString szFileName=""; CString csFileName="";
 CString szFileDir="";

 CString csTmp="";  CString csCh=""; CString csLoad="";

// CFileDialog filedlg(TRUE,_T(""),_T(csTmp),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,//열기
 CFileDialog filedlg(FALSE,_T(""),_T(csTmp),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,//저장  
  "Save AS Excel CSV Files (*.csv)|*.csv||",NULL);//"files (*.*)",NULL);

 if (filedlg.DoModal()==IDOK)
 {
 szFileDir=filedlg.GetPathName();   AfxMessageBox(szFileDir);//전체 화일+확장자까지
 szFileName=filedlg.GetFileTitle();    AfxMessageBox(szFileName);//입력 화일명만  
 szFileName=filedlg.GetFileName();      AfxMessageBox(szFileName);//입력 화일과 확장자 까지

 //화일명 뺀 화일 Dir
 int index1=0; int index2=0; int nMode=0;
 index1=szFileDir.GetLength(); index2=szFileName.GetLength();
 csTmp=szFileDir.Mid(0,(index1-index2));


 
 szFileName=csTmp; AfxMessageBox(szFileName);
 //_mkdir(szFileName);
 }
 
 //===읽기========================================================
 //---------------------------------------------------------------
 csFileDir=filedlg.GetPathName(); //전체 디렉토리+화일명+확장자
 csFileName=filedlg.GetFileName();//화일명+확장자
 //---------------------------------------------------------------
 CString strFilter;
 strFilter.LoadString(AFX_IDS_PICTUREFILTER);

 CString strTitle;
 strTitle.LoadString(AFX_IDS_PICTUREBROWSETITLE);

 CFileDialog fdlg(TRUE, NULL, NULL,
   OFN_FILEMUSTEXIST |
   OFN_HIDEREADONLY |
   OFN_PATHMUSTEXIST,
   strFilter);

 fdlg.m_ofn.lpstrTitle = strTitle;

 int nResult = fdlg.DoModal();
 SetFocus();

 if (nResult != IDOK)
  return;

 CString strPath = fdlg.GetPathName();
 //---------------------------------------------------
 CString csFileName="";
 CString csFileDir="";
 CString csOpenDir; csOpenDir=CSProgramDir+CSFileSpecDataDir+CSDriveDataFileName+"\\";

 CFileDialog filedlg(TRUE,_T("*.INI"),_T(csOpenDir),OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
  "INI files (*.ini)|*.ini||",NULL);

 if (filedlg.DoModal()==IDOK)
 {
  csFileDir=filedlg.GetPathName();
  CString csTmp;CString csBuf; CString csImage;
  if(csFileDir.GetLength()>0)
  {
  UpdateData(TRUE);
  CString csDriveName=csFileDir;
  CString filename = csDriveName;//+".ini";
  FileData_UpdateCommandData(filename);
  CommandDataUpdateDisplay();
  UpdateData(FALSE);
  }
 }

 //------------------------------------------------------------------
 CString szFileName;

 CFileDialog filedlg(TRUE,"bmp",NULL,OFN_FILEMUSTEXIST,
  "BMP files (*.bmp)|*.bmp||",NULL);
// if (freezeMode==FREEZE_BITMAP)
 {
  if (filedlg.DoModal()==IDOK)
  {
  szFileName=filedlg.GetPathName();
  szFileName=filedlg.GetFileName();
  }
 }
 
       //-----------------------------------------------------------
 int result;
 result=filedlg.DoModal();

 switch(result)
 {
 case IDOK:
  szFileName=filedlg.GetPathName();
   break;
 }
   return;

/=======================================================================================
//    화일
//======================================================================================

//==============화일 GetPrivateProfileString==================================================
      char Retemp[256];
      char Lotemp[256];
      char Filetemp[2048];
      char Postemp[256];

     //상대 주소 -PLC
 GetPrivateProfileString("CONFIG","REMOTE_ADDR","192.168.001.1",Retemp,256,".\\config.ini");
 int iRePort = GetPrivateProfileInt("CONFIG","REMOTE_PORT",20000,".\\config.ini");
 //현재 주소 -PC
    GetPrivateProfileString("CONFIG","LOCAL_ADDR","192.168.001.200",Lotemp,256,".\\config.ini");
 int iLoPort = GetPrivateProfileInt("CONFIG","LOCAL_PORT",20001,".\\config.ini");

 // 작업모델 화일 Dir
    GetPrivateProfileString("FILE","FILENAME","DataSpec.ini",Filetemp,2048,".\\config.ini");

 CSFileSpecFileName=Filetemp;
 FileData_DataSysGet(CSFileSpecFileName,FILE_SPEC);

 // 카메라 X 위치 옵셋
    GetPrivateProfileString("AXIS","CAM_POS_X","20",Postemp,256,".\\config.ini");
 m_fCamOffsetPos_X=(float)atof((LPCSTR)Postemp);

 // 카메라 Y 위치 옵셋
    GetPrivateProfileString("AXIS","CAM_POS_Y","20",Postemp,256,".\\config.ini");
 m_fCamOffsetPos_Y=(float)atof((LPCSTR)Postemp);


//==============화일 WritePrivateProfileString==================================================
    char temp[256];
    char Filetemp[2048];

    memset(Filetemp, 0, 2048);
    lstrcat(Filetemp, SEQ.csSpecFileName);

    WritePrivateProfileString("FILE","FILENAME",Filetemp,CSProgramDir+"\\config.ini");

    GetDlgItemText(IDC_LISTEN_EDIT,temp,256);
    WritePrivateProfileString("CONFIG","LISTEN_PORT",temp,CSProgramDir+"\\config.ini");

//=======================================================================================
 FILE  *inn;
 int   i;
 CString  fstr = SysDir;
 fstr += "\\calibration.rsl";

 if( (inn= fopen(fstr,"r") ) != NULL )
 {
  for(i=0;i<7;i++)
   fscanf(inn,"%lf",&m_Calib.Val[i]);
  fclose(inn);
 }
 else
  AfxMessageBox("File could not be opened.",MB_OK,0);
 
//=======================================================================================
 FILE  *inn;
 CString  fstr = SysDir;
 fstr += "\\rotate.rsl";

 if( (inn= fopen(fstr,"w") ) != NULL )
 {
  fprintf( inn, "%lf %lf %lf %lf\n",m_Rotate.a,m_Rotate.b,m_Rotate.c,m_Rotate.d);
  fclose(inn);
 }
 else
  AfxMessageBox("File could not be opened.",MB_OK,0);

//===============화일 복사===============================================================

 sFileName=strSelectedPath + "\\" + "Pcb.dat";
 tFileName=strBackUpPath + "\\" +"Pcb.dat";
 CopyFile(sFileName, tFileName , false);

//===============확장자 검색=============================================================

  fileName=fileDlg.GetPathName();
  CString ext=fileName.Right(4);

  if (!ext.CompareNoCase(".JPG"))
  {
  // AX_LoadJPG(fileName);
  // SetDlgItemText(IDC_FILEDIR_STATIC, fileName);
  }

  if (!ext.CompareNoCase(".BMP"))
  {
   LoadBMPToSet(fileName);
  // SetDlgItemText(IDC_FILEDIR_STATIC, fileName);
  }

//=======================================================================================

 FILE *fp;

 fp=fopen(fileName,"rb");
 if (fp==NULL) {
  CString msg;                   
  msg="Can't open file for reading :\n"+fileName;
  m_errorText=msg;
  return NULL;
 }
 else
 {
  if (fread((void  *)(pixel),1,3,fp)==3)
  {
   *(outBuf+ADDr)=pixel[2];  // r
   *(outBuf+ADDg)=pixel[1];  // g
   *(outBuf+ADDb)=pixel[0];
  }
 }
 fclose(fp);

//=====================================================================================

 HFILE fi;

 CString Contents=csData; CString csfilename="";
// csfilename=CSFileTestDataDir+csFileName;
 csfilename =FileData_TestFileDirChk(csFileName, nMode, nCh);
 fi=_lopen(csfilename,OF_READWRITE);
 int len;
 len=_lwrite(fi,(LPCSTR)m_csTestFileData[nCh],strlen(m_csTestFileData[nCh]));
 _lclose(fi);

/*------파일 -------------------------------------------------------*/
 CString   csfilename=_T(""); CString   Contents=_T("");

 if(nCh>=CHMAX) return Contents;
// filename = CSFileTestDataDir+csFileName;
 csfilename =FileData_TestFileDirChk(csFileName, FILE_CSV, nCh);

 CFile file(csfilename,CFile::modeReadWrite|CFile::shareExclusive);
// CFile file("C:\\Polaronix\\Data\\Ch01.csv",CFile::modeReadWrite |CFile::shareExclusive);
 DWORD filesize=file.GetLength();
 char *buf=new char[filesize+1];

 file.Read(buf,filesize);
 file.Close();

 buf[filesize]=NULL;
 Contents=LPCSTR(buf);   delete buf;
 return Contents;

/*------파일 -------------------------------------------------------*/
 CString csData="";
 char* pFileName = "C:\\Polaronix\\Data\\Ch01.csv";
 CStdioFile file;
 if( !file.Open( pFileName,
  //  | CFile::modeWrite | CFile::typeText ) ) {
   CFile::modeRead | CFile::typeText ) ) {  
 }
 file.ReadString(csData);
 AfxMessageBox(csData);
 file.Close();
 
/*------파일 Open--------------------------------------------------*/
 csBmpFile=_T("Bin\\bmp3_96.bin");

 CFile *aFile;
 try
 {
  aFile=new CFile(csBmpFile,CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite | CFile::shareDenyNone);
 }
 catch(CFileException *e)
 {
  e->Delete();
 }
 aFile->Abort(); //파일 닫기 실한 경우 예외 발생 않함
// aFile->Close();
// delete aFile;


 CString csBmpFile;
 csBmpFile=_T("Bin\\bmp1_128.bin");

 CFile *aFile;
 try
 {
 // UINT readByte;
  aFile=new CFile(csBmpFile,CFile::modeNoTruncate|CFile::modeReadWrite|CFile::shareDenyNone);

  if(m_ZoomSize_X==96)
  {
  aFile->Write(temp2,12288);
  }
  else
  {
  aFile->Write(temp2,24576);
  }
 }
 catch(CFileException *e)
 {
  e->Delete();
 }

 aFile->Abort(); //파일 닫기 실패한 경우 예외 발생 않함
// aFile->Close();
// delete aFile;

/*------파일 Open--------------------------------------------------*/

 HFILE fi;
 fi=_lopen("Bin\\bmp.bin",OF_READWRITE);

 int len;
 len=_lwrite(fi,(LPCSTR)temp1,strlen(temp1));

 _lclose(fi);


 FILE *fp;
 filename="Bin\\bmp.bin";

 if ((fp = fopen(filename,"w+")) == NULL) {
  AfxMessageBox("File Open Error.");  
  fclose(fp);
  return ;
 }
// Contents.Insert(Contents.GetLength(),
// Contents.Format(csBmp);
 fwrite(Contents,1,Contents.GetLength(),fp);
 fclose(fp);

/*------파일 Open--------------------------------------------------*/
#SETUP$
DF34257
CAS124T0
AS1234DF
SDFG4321
#ENDEQ$

void CSBottleView::FileDataUpdate(int nMode)
{
 CString csItemNameSelectFileName=_T("EquipSys\\ItemNameSelect.ini");

 __int16   length, exist;
 char   str[200];
 int index=0;
 int nCount=0;

 FILE   *fp ;
 CString   filename=_T("");
 CString   ReadData=_T("");
 CString   strTmp=_T("");
 BOOL   bFileCheck=false;
 BOOL   bFileCheck2=false;

 m_csModelItemName[1]=_T("");
 m_csModelItemName[2]=_T("");
 m_csModelItemName[3]=_T("");
 m_csModelItemName[4]=_T("");


 if(nMode==ITEMNAME)
 filename = csItemNameSelectFileName;
 else return;

 exist = access(filename,0);

 if (!exist && (fp = fopen(filename,"rt")) != NULL) {
  while (!feof(fp)) {
   ReadData.Empty();
   if ( fgets(str, 200, fp) != NULL) {   // error Return NULL
    ReadData.Format("%s", str);
    length = ReadData.GetLength();

    if(bFileCheck2==false)
    {
    index = ReadData.Find("#SETUP$");
    if(index>=0){bFileCheck=true; index=0; }
    else{AfxMessageBox("설정 데이타가 없습니다 !"); break;}
    }

    index = ReadData.Find("\t");
    if(index>=0)
    {
    ReadData.Format("%s", ReadData.Mid(0 , length-2));
    }
    else
    {
    ReadData.Format("%s", ReadData.Mid(0 , length-1));
    }
 
    if(ReadData=="#ENDEQ$"){break;}

    if(bFileCheck)
    {
     if(bFileCheck2)
     {
      if(nCount>=60){AfxMessageBox("저장된 데이타가 너무많습니다");break;}
     
      if(nCount==0)
      {m_csModelItemName[1]=ReadData;}
      else if(nCount==1)
      {m_csModelItemName[2]=ReadData;}
      else if(nCount==2)
      {m_csModelItemName[3]=ReadData;}
      else if(nCount==3)
      {m_csModelItemName[4]=ReadData;}
      nCount++;
     }
    }
       bFileCheck2=true;
   }
  }
 /// fclose(fp);

 } else {
  AfxMessageBox("설정데이타가 없습니다!  ItemNameSelect.data 화일이 없습니다."); return;//return 않하면 프로그램 에러
 }
 fclose(fp);

 UpdateData(FALSE);
}

/*------파일 Open--------------------------------------------------*/

 FILE *fpRobot;
 CString str;

 fpRobot = fopen("robot.txt", "rw+");
 fprintf(fpRobot, "%s", str);
 fclose( fpRobot );


/*------파일 생성 및 NotePad로 실행--------------------------------------------------*/
 FILE *fp;
 CString Contents, datename, filename;

 filename="test.txt";

 if ((fp = fopen(filename,"w+")) == NULL) {
  AfxMessageBox("File Open Error.");  
  fclose(fp);
  return ;
 }

 Contents.Format("\r\n=== FILE INFORMATION ===\r\n");
 Contents.Insert(Contents.GetLength(),"\r\nDATE & TIME\t");
 Contents.Insert(Contents.GetLength(),datename);

 Contents.Insert(Contents.GetLength(),"\r\nOPERATOR\t");

 Contents.Insert(Contents.GetLength(),"\r\n\r\nFile Name\t");
 Contents.Insert(Contents.GetLength(),filename);
 Contents.Insert(Contents.GetLength(),"\r\n\r\n");

 Contents.Insert(Contents.GetLength(),"=== ERROR LISTS ===\r\n\r\n");

 Contents.Insert(Contents.GetLength(),
  " ERR TIME\tCODE\tERROR MESSAGE                  \tOPERATORr\n\r\n");

 fwrite(Contents,1,Contents.GetLength(),fp);
 fclose(fp);

 char csNote[128];
 strcpy(csNote,"c:\\Windows\\NOTEPAD ");
 strcat(csNote,filename);
 WinExec(csNote,SW_SHOW);

/*----------------다른 폴더에서 파일copy 후 다른이름으로 저장 -------------*/ 
 SHFILEOPSTRUCT sfo;
 memset(&sfo,0,sizeof(sfo));
 sfo.wFunc = FO_COPY;
 sfo.pFrom = _T("C:\\Aatool\\equip1.dat\0");
 sfo.pTo = _T("C:\\DATA\\suho.dat\0");
/* sfo.wFunc = FO_RENAME;
 sfo.pFrom = _T("C:\\DATA\\equip1.dat\0");
 sfo.pTo = _T("C:\\DATA\\ok.dat\0");
*/
 SHFileOperation(&sfo);


/*----------------여러 화일 삭제 -----------------------------------------------------------*/
 SHFILEOPSTRUCT sfo;
 memset(&sfo,0,sizeof(sfo));
 sfo.wFunc = FO_DELETE;
 sfo.fFlags =OFN_SHOWHELP; //메시지 창 뛰우지 않음
 sfo.pFrom = _T("Bmp\\*.*");
 SHFileOperation(&sfo);


/*------------------------------화일삭제--DeleteFile---------------------------------------*/

 UpdateData(TRUE);
   CCPKView* pView =( CCPKView* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();
 
 CCPKDoc *pDoc;
 pDoc=pView->GetDocument();

 int year,month;
 year=month=0;
 year=2001;
 month=5;

 if(AfxMessageBox(" ''Are You Sure ! DataBase delete ?'' ",MB_ICONQUESTION|MB_YESNO)==IDYES)
 {
   pDoc->DeleteDB(year,month);
  }
 else
  {
   return;
 }

void CCPKDoc::DeleteDB(int year, int month)
{
 CString csFile;
 
 csFile.Format("DATA\\CPK%4d%02d.mdb", year, month);
 DeleteFile((LPCTSTR)csFile);
 
 csFile.Format("DATA\\CPK%4d%02d.ldb", year, month);
 DeleteFile((LPCTSTR)csFile);
}
 
 SHFILEOPSTRUCT sfo;
 memset(&sfo,0,sizeof(sfo));
 sfo.wFunc = FO_DELETE;
 sfo.pFrom = _T("C:\\DATA\\200101.mdb\0");
 SHFileOperation(&sfo);

/*----------------------------------Windows 레지스트리에 저장-----------------------*/
void CPSRecorderView::INI_Get()
{
 char buff[1024];
 CString m_csTmpString;
 m_csTmpString = "NONE";
 GetPrivateProfileString("TIME", "TESTTIME1", m_csTmpString.operator const char * (), (LPTSTR)buff, 20, "SAET32.INI");
 m_fTestTime1= (float)atof((LPCSTR)buff);
}

void CPSRecorderView::INI_Write()
{
 CString m_csTmpString;
 m_csTmpString = "NONE";
 m_csTmpString.Format("%0.1f", m_fTestTime1);
 WritePrivateProfileString("TIME", "TESTTIME1", m_csTmpString.operator LPCTSTR(), "SAET32.INI");
}

/*----------------------------------BMP File저장-------------------------------------*/
void CCoilView::OnSaveimg() {
CFileDialog filedlg(FALSE,"bmp",NULL,OFN_OVERWRITEPROMPT,
 "BMP files (*.bmp)|*.bmp||",this);
 if (filedlg.DoModal()!=IDOK)
  return;
CColorBmpFile bmp;
 bmp.OpenWrite(filedlg.GetPathName(),640,480);
 for (int y=479; y>=0; y-=2) {
 BYTE rbuffer[640],gbuffer[640],bbuffer[640];
  Data->GetLine(y,rbuffer,gbuffer,bbuffer);
  bmp.WriteLineUpward(rbuffer,gbuffer,bbuffer);
  bmp.WriteLineUpward(rbuffer,gbuffer,bbuffer);
 }
 bmp.Close();
 m_strMessage = "저장되었습니다.";
 UpdateData(FALSE);
}


/*----------------------------------goto-------------------------------------*/
 goto fail;
 
 fail:
 MessageBox(NULL,"에러 입니다.","오류",MB_OK);
 return FALSE;

/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 이미지 -  ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

#define WIDTHBYTES(bits) ((DWORD)(((bits)+31) & (~31)) / 8)
#define WIDTHBYTES(bits)    (((bits) + 31) / 32 * 4)


//======Center부터 검색 ======================================================================================
 //===CenterSearch===========================
 int x2=0, y2=0;
 int half_x=width/2; int half_y=height/2;
 float direct_y=-1; float direct_x=-1;
 int Cnt_y1=0;int Cnt_y2=0;
 int Cnt_x1=0;int Cnt_x2=0;
 //==========================================

 for(y=0; y<height-tHeight; y++)
 {
  //=====CenterSearch===================================
  Cnt_y1++;
  if(Cnt_y1>=2){Cnt_y1=0;Cnt_y2++;}
  if(direct_y==1)direct_y=float(-1); else direct_y=1;
  y2=int( half_y + (Cnt_y2* direct_y) );
  Cnt_x1=0; Cnt_x2=0; direct_x=-1;
  //===================================================
  for(x=0; x<width-tWidth; x++)
  {
   //=====CenterSearch================================
              Cnt_x1++;
   if(Cnt_x1>=2){Cnt_x1=0;Cnt_x2++;}
   if(direct_x==1)direct_x=float(-1); else direct_x=1;
   x2=int( half_x + (Cnt_x2* direct_x) );
   //=================================================

   pDC.SetPixel(x2+100,y2+100,RGB(255,0,0));

  }
 }
//==========================================================================================================
void ReadArrayToPointBit24(BYTE * OutImg, unsigned char BufImg[768][1024], UINT width, UINT height)
{
 CVisionSysView* pView =( CVisionSysView* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();
 CDC *pDC =pView->GetDC();
 //GrayImage =width*3;
 //Dispay Image= ((24*width)+31)/32*4), ((DWORD)(((bits)+31) & (~31)) / 8)
 //if(BufImg==NULL) return;
 int x,y; int y2=0;
 int nBit=0; nBit=24;

 int rwsize = WIDTHBYTES(nBit*width);

 int ADDr=0,ADDg=0,ADDb=0;
  if(BufImg!=NULL)
  {
   for(y=0; y<nHeight; y++)
   {
    for(x=0; x<nWidth; x++)
    {
     y2=((height-1)-y);//-1 은 첫줄이 않나옴, y가 0일경우 문제
    // y2=y;//-1 은 첫줄이 않나옴, y가 0일경우 문제

     ADDr=(y2*rwsize)+(3*x)+2;
     ADDg=(y2*rwsize)+(3*x)+1;
     ADDb=(y2*rwsize)+(3*x)+0;

    // BufRevImg[ADDr]=BufImg[y][x];
    // BufRevImg[ADDg]=BufImg[y][x];
    // BufRevImg[ADDb]=BufImg[y][x];
     *(OutImg+ADDr)=BufImg[y][x];
     *(OutImg+ADDg)=BufImg[y][x];
     *(OutImg+ADDb)=BufImg[y][x];
    // pDC->SetPixel(x+400,y,RGB(BufImg[ADDr],BufImg[ADDg],BufImg[ADDb]));
    // pDC->SetPixel(x+400,y,RGB(BufImg[y][x],BufImg[y][x],BufImg[y][x]));
    }
   }
  }
}

//==========================================================================================================
void CVisionSysView::OnDraw(CDC* pDC)
{
 // TODO: Add your specialized code here and/or call the base class
 CVisionSysDoc* pDoc = GetDocument();
 ASSERT_VALID(pDoc);
 CMainFrame *pFrame= (CMainFrame*)AfxGetMainWnd();
 ASSERT(pFrame);

/// return;
 int height=m_height;int width=m_width;  int Bit=m_Bit;
 int rwsize = WIDTHBYTES(Bit*width);
 BITMAPINFOHEADER bmiHeader;
 bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
 bmiHeader.biWidth = width;  bmiHeader.biHeight = height;
 bmiHeader.biPlanes = 1;  
 bmiHeader.biBitCount = Bit;
 bmiHeader.biCompression = BI_RGB;
 bmiHeader.biSizeImage = rwsize*height;//0; 
 bmiHeader.biXPelsPerMeter = 0;
 bmiHeader.biYPelsPerMeter = 0;bmiHeader.biClrUsed = 0;
 bmiHeader.biClrImportant = 0;// CRect rect;
 CRect rect;

 //=================================================================
 //--Open Gray Image--
 if(m_ColorGetImg!=NULL)//COLOR_IMAGE, SPOT_IMAGE, AUOT_IMAGE
 {
///  CPaintDC dcView(GetDlgItem(IDC_IMG_VIEW));
///  dcView.SetStretchBltMode(STRETCH_DELETESCANS);
///  GetDlgItem(IDC_IMG_VIEW)->GetClientRect(&rect);

//  StretchDIBits(dcView.m_hDC,rect.left,rect.top,rect.right,rect.bottom,
///  StretchDIBits(dcView.m_hDC,rect.left,rect.top,width,height,
//  StretchDIBits(pDC->GetSafeHdc(),20,20,width,height,
//  0, 0,width, height, m_ColorGetImg, (LPBITMAPINFO)&dibHi, DIB_RGB_COLORS, SRCCOPY);
///  0, 0,width, height, m_GrayImg, (LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS, SRCCOPY);
 
//  SetDIBitsToDevice(pDC->GetSafeHdc(),0,0,width,height,
//      0,0,0,height,m_GrayImg,(LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS);
//  DibDraw(pDC,0,0,height,width,m_ColorGetImg,24);
  if(m_GrayImg!=NULL)DibDraw(pDC,0,0,height,width,m_GrayImg,Bit);
//  DibDrawReverse(pDC,0,0,height,width,m_GrayImg,24);
 }
 //=================================================================
 if(m_OutImg!=NULL)//이미지 가감 처리영상
 {
  int Add=640;
  DibDrawArrayToBit24(pDC,0+Add,0,height,width,m_OutImg,24);
 }
 //=================================================================
 // 마우스 드레그-템플레이트 정합을 위한 부분
 if(m_flagMouse==TRUE)
 {
  //pDC->DrawEdge(&m_RectTrack,EDGE_ETCHED,BF_RECT);
  DrawRect(pDC, m_RectTrack, RGB(0,0,255), 2);
 }
 if(pFrame->m_flagTemplate==TRUE) // template가 설정되어 있는 경우
 {
  if(m_TempImg!=NULL)
  {
   DibDrawBit8(pDC,width+40,0,tHeight,tWidth,m_TempImg,24);
   rect.left=width+40; rect.top=0;
   rect.right=rect.left+tWidth;  rect.bottom=rect.top+tHeight;
   DrawRect(pDC, rect, RGB(255,0,0), 2);
  }
 }
 //==================================================================
 //--이미지 검색 결과
 if(!(m_MatchPos.right==0 && m_MatchPos.bottom==0))
 {
  if(m_bImageSearch)
  {
  // pDC->DrawEdge(&m_MatchPos,EDGE_BUMP,BF_RECT);  
   DrawRect(pDC, m_MatchPos, RGB(255,0,0), 2);
   m_bImageSearch=FALSE;
  }
 }
 //==================================================================
 CClientDC pDC(this);

 int width=m_width;int height=m_height;
 if(m_ColorGetImg!=NULL)//COLOR_IMAGE, SPOT_IMAGE, AUOT_IMAGE
 {
//  CPaintDC dcView(GetDlgItem(IDC_IMG_VIEW));
//  dcView.SetStretchBltMode(STRETCH_DELETESCANS);
//  GetDlgItem(IDC_IMG_VIEW)->GetClientRect(&rect);
//  StretchDIBits(dcView.m_hDC,rect.left,rect.top,rect.right,rect.bottom,
//  StretchDIBits(dcView.m_hDC,rect.left,rect.top,width,height,
//  0, 0,width, height, m_ColorGetImg, (LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS, SRCCOPY);
  StretchDIBits(pDC.GetSafeHdc(),20,20,width,height,
  0, 0,width, height, m_ColorGetImg, (LPBITMAPINFO)&dibHi, DIB_RGB_COLORS, SRCCOPY);
 
//  SetDIBitsToDevice(pDC->GetSafeHdc(),0,0,width,height,
//      0,0,0,height,m_ColorGetImg,(LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS);
 }

//---------BMP File Save------------------------------------------------------------------------
 //BMP File Save
 int ImageMaxNo=1;
 BITMAPINFOHEADER dibHi;
 BITMAPFILEHEADER dibHf;/// CClientDC pDC(this);
 int ADD1=0; int ADD2=0; int ADD3=0;
 int x=0; int y=0; int y2=0;
 int WidthLineSize=WIDTHBYTES(24*width);
 int WidthLineSize2=WIDTHBYTES(8*width);
 unsigned char *BmpOutImg=NULL;
 BmpOutImg = new unsigned char [(height*ImageMaxNo)*(width*24)*3];

 BmpOutImg =buf;

 for(y=0; y<height*ImageMaxNo; y++) //BMP 화일로 저장 하기위해 거꾸로 저장
 {
  y2=((height*ImageMaxNo)-y);//-1 중요(최종 한줄 표현)
  for(x=0; x<width; x++)
  {
   ADD1=(y2*WidthLineSize)+(3*x)+2;
   ADD2=(y2*WidthLineSize)+(3*x)+1;
   ADD3=(y2*WidthLineSize)+(3*x)+0;

   BmpOutImg[(y2*WidthLineSize)+(3*x)+2]=buf[(y*WidthLineSize)+(3*x)+2];
   BmpOutImg[(y2*WidthLineSize)+(3*x)+1]=buf[(y*WidthLineSize)+(3*x)+1];
   BmpOutImg[(y2*WidthLineSize)+(3*x)+0]=buf[(y*WidthLineSize)+(3*x)+0];
  // pDC->SetPixel(x+500,y,RGB(BmpOutImg[ADD1],BmpOutImg[ADD2],BmpOutImg[ADD3]));
  }
 }

 DWORD dwBitsSize = sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256+WidthLineSize*height*sizeof(char);
 
 dibHi.biSize=40;
 dibHi.biWidth=width;
 dibHi.biHeight=height*ImageMaxNo;
 dibHi.biPlanes=1;
 dibHi.biBitCount =24;
 dibHi.biCompression=BI_RGB;
 dibHi.biSizeImage = 3*WidthLineSize*(height*ImageMaxNo);
 dibHi.biXPelsPerMeter=0;
 dibHi.biYPelsPerMeter=0;
 dibHi.biClrUsed = dibHi.biClrImportant =0;
 
 dibHf.bfType=0x4D42;
 dibHf.bfSize = dwBitsSize+sizeof(BITMAPFILEHEADER); // 전체파일 크기
 if(dibHi.biBitCount==24) dibHf.bfSize -= sizeof(RGBQUAD)*256; // no pallette
 dibHf.bfOffBits = dibHf.bfSize - WidthLineSize*height*sizeof(char);
 dibHf.bfReserved1=dibHf.bfReserved2=0;

 FILE *outfile2;
 CString csFile; csFile.Format("C:\\Data\\D1_Project\\두오텍\\VisionSys\\bmp\\spec.bmp");
 outfile2 = fopen(csFile,"wb");

 fwrite(&dibHf,sizeof(char),sizeof(BITMAPFILEHEADER),outfile2);
 fwrite(&dibHi,sizeof(char),sizeof(BITMAPINFOHEADER),outfile2);
 fwrite(BmpOutImg,sizeof(char),3*WidthLineSize*dibHi.biHeight,outfile2);
// fwrite(buf,sizeof(char),3*WidthLineSize*dibHi.biHeight,outfile2);
 fclose(outfile2);
 if(BmpOutImg) delete []BmpOutImg;

//------------------------------------------------------------------------------------------------------------------------
void CNG::OnPaint()
{
 CPaintDC pDC(this); // device context for painting
 
 // TODO: Add your message handler code here
 if (m_ColorImg==NULL) return;

 int height=m_height;int width=m_width;
 int rwsize = WIDTHBYTES(24*width);

 BITMAPINFOHEADER bmiHeader;
 bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
 bmiHeader.biWidth = width;  bmiHeader.biHeight = height;
 bmiHeader.biPlanes = 1;    bmiHeader.biBitCount = 24;bmiHeader.biCompression = BI_RGB;
 bmiHeader.biSizeImage = rwsize*height;//0; 
 bmiHeader.biXPelsPerMeter = 0;
 bmiHeader.biYPelsPerMeter = 0;bmiHeader.biClrUsed = 0;
 bmiHeader.biClrImportant = 0;// CRect rect;
 
 CRect rect;

 if(m_ColorImg!=NULL)//COLOR_IMAGE, SPOT_IMAGE, AUOT_IMAGE
 {
  CPaintDC dcView(GetDlgItem(IDC_IMAGE1));
  dcView.SetStretchBltMode(STRETCH_DELETESCANS);
  GetDlgItem(IDC_IMAGE1)->GetClientRect(&rect);

  StretchDIBits(dcView.m_hDC,rect.left,rect.top,rect.right,rect.bottom,
//  StretchDIBits(dcView.m_hDC,rect.left,rect.top,width,height,
//  StretchDIBits(pDC->GetSafeHdc(),20,20,width,height,
//  0, 0,width, height, m_ColorGetImg, (LPBITMAPINFO)&dibHi, DIB_RGB_COLORS, SRCCOPY);
  0, 0,width, height, m_ColorImg, (LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS, SRCCOPY);
 
//  SetDIBitsToDevice(pDC.GetSafeHdc(),0,0,width,height,
//      0,0,0,height,m_ColorGetImg,(LPBITMAPINFO)&bmiHeader, DIB_RGB_COLORS);
 }
 // Do not call CDialog::OnPaint() for painting messages
}

//-----------------------------------------------------------------------------------------------------------------------
void DibDraw(CDC *pDC, int px, int py, int height, int width, BYTE *BufImg, int Bit)
{
 int x,y; int y2=0;
 int nBit=0; nBit=Bit;
 int rwsize = WIDTHBYTES(nBit*width);//(((8*width)+31)/32*4);  // 4바이트의 배수여야 함
 BITMAPINFO *BmInfo;
 BmInfo = (BITMAPINFO*)malloc(sizeof(BITMAPINFO)+256*sizeof(RGBQUAD));

 BmInfo->bmiHeader.biBitCount=nBit;
 BmInfo->bmiHeader.biClrImportant=256;//0
 BmInfo->bmiHeader.biClrUsed=256;//0
 BmInfo->bmiHeader.biCompression=BI_RGB;//0

 BmInfo->bmiHeader.biHeight = height;
 BmInfo->bmiHeader.biPlanes=1;
 BmInfo->bmiHeader.biSize=40;//=sizeof(BITMAPINFOHEADER);

 if(nBit==24)
 BmInfo->bmiHeader.biSizeImage=rwsize*height*3;
 else
 BmInfo->bmiHeader.biSizeImage=rwsize*height;

 BmInfo->bmiHeader.biWidth =width;
 BmInfo->bmiHeader.biXPelsPerMeter=0;
 BmInfo->bmiHeader.biYPelsPerMeter=0;

 for(x=0; x<256; x++) // Palette number is 256
 {
  BmInfo->bmiColors[x].rgbRed= BmInfo->bmiColors[x].rgbGreen = BmInfo->bmiColors[x].rgbBlue = x;
  BmInfo->bmiColors[x].rgbReserved = 0;
 }

 if(nBit==24)
 {
  int ADDr=0,ADDg=0,ADDb=0;
  int ADDr2=0,ADDg2=0,ADDb2=0;
  unsigned char *BufRevImg = new unsigned char [(width*24)*height*3];
  /*
  if(BufImg!=NULL)
  {
   for(y=0; y<height; y++)
   {
    for(x=0; x<width; x++)
    {
     y2=((height-1)-y);//-1 은 첫줄이 않나옴, y가 0일경우 문제
     ADDr=(y*rwsize)+(3*x)+2;
     ADDg=(y*rwsize)+(3*x)+1;
     ADDb=(y*rwsize)+(3*x)+0;

     ADDr2=(y2*rwsize)+(3*x)+2;
     ADDg2=(y2*rwsize)+(3*x)+1;
     ADDb2=(y2*rwsize)+(3*x)+0;

     BufRevImg[ADDr]=BufImg[ADDr2];
     BufRevImg[ADDg]=BufImg[ADDg2];
     BufRevImg[ADDb]=BufImg[ADDb2];
    // pDC->SetPixel(x+400,y,RGB(BufImg[ADDr],BufImg[ADDg],BufImg[ADDb]));
    }
   }
  }
 */
  int ImgSize=(width*24)*height*3;//int ImgSize=(width*8)*height;//8
  memcpy(BufRevImg,BufImg,ImgSize);
 // SetDIBitsToDevice(pDC->GetSafeHdc(),px,py,width,height,
 //     0,0,0,height,BufImg,(LPBITMAPINFO)&dibHi, DIB_RGB_COLORS);
 // SetDIBitsToDevice(pDC->GetSafeHdc(),px,py,width,height,
 //     0,0,0,height,BufImg,BmInfo, DIB_RGB_COLORS);
  SetDIBitsToDevice(pDC->GetSafeHdc(),px,py,width,height,
      0,0,0,height,BufRevImg,BmInfo, DIB_RGB_COLORS);
  delete []BufRevImg;
 }
 else
 {
  unsigned char *BufRevImg = new unsigned char [height*rwsize];
  int index1,index2=0;
  for(y=0; y<height; y++)
  {
   index1 = y*rwsize;
   index2 = (height-y-1)*width;
  // index2 = y*width;
   for(x=0; x<width; x++)
   {
    BufRevImg[index1+x]=BufImg[index2+x];
   // pDC->SetPixel(j,i,RGB(BufImg[index2+x],BufImg[index2+x],BufImg[index2+x]));
   }
  }

  SetDIBitsToDevice(pDC->GetSafeHdc(),px,py,width,height,
      0,0,0,height,BufRevImg,BmInfo, DIB_RGB_COLORS);
  delete []BufRevImg;
 }

}
//-----------------------------------------------------------------------------------------------------------------------
void CNG::AX_LoadJPG(CString fileName)
{
 UINT width=427; UINT height=601;
 
 if (m_ColorGetImg!=NULL) {delete [] m_ColorGetImg;m_ColorGetImg=NULL;}
 if (m_ColorImg!=NULL)  {delete [] m_ColorImg;m_ColorImg=NULL;}
 m_ColorImg = new unsigned char [(width*24)*height*3];

 // read to buffer tmp
 m_ColorGetImg=JpegFile::JpegFileToRGB(fileName, &width, &height);
 //CString csTmp; csTmp.Format("%d, %d",width, height); AfxMessageBox(csTmp);
 //-------------------------------------------------------
 if(m_ColorGetImg==NULL){return;}
 //-------------------------------------------------------
 JpegFile::BGRFromRGB(m_ColorGetImg, width, height);
 // vertical flip for display
 JpegFile::VertFlipBuf(m_ColorGetImg, width * 3, height);
 m_width=width; m_height=height;

 int y=0;
 int x=0;
 int ADD1,ADD2,ADD3;
 int SUM1,SUM2,SUM3;

 #define WIDTHBYTES2(bits)    (float((bits) / float(32)) * 4)

 float rwsize=WIDTHBYTES2(24*(width));//이미지 Size홀수 문제
 int   rwsize2=WIDTHBYTES(24*(width));

  for(y=0; y<int(height); y++)
  {
   for(x=0; x<int(width); x++)
   {
   ADD1=int((y*rwsize)+(3*x)+2);
   ADD2=int((y*rwsize)+(3*x)+1);
   ADD3=int((y*rwsize)+(3*x)+0);

   SUM1=int((y*rwsize2)+(3*x)+2);
   SUM2=int((y*rwsize2)+(3*x)+1);
   SUM3=int((y*rwsize2)+(3*x)+0);

   m_ColorImg[SUM1]=m_ColorGetImg[ADD1];
   m_ColorImg[SUM2]=m_ColorGetImg[ADD2];
   m_ColorImg[SUM3]=m_ColorGetImg[ADD3];
   
   //pDC.SetPixel(nX,nY,RGB(m_ColorImg[SUM1],m_ColorImg[SUM2],m_ColorImg[SUM3]));
   }

  }
}
//--------------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - POINT -  /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

//======MEMCPY 생성=======================================================================

 unsigned char *OutImg = NULL;
// OutImg = new unsigned char [(nWidth*Bit)*nHeight*3];
 OutImg = (unsigned char*)calloc(nWidth*Bit*nHeight*3,sizeof(char));

 BYTE *outBuf=NULL;

 long bufsize = (long)w * 3 * (long)h;
 outBuf=(BYTE *) new BYTE [bufsize];

 outBuf=NULL;
 outBuf = new unsigned char [bufsize]; //dibHi.biSizeImage
// outBuf=(BYTE *) new BYTE [bufsize];


//======MEMCPY============================================================================

 int ImgSize=(width*24)*height*3;//24
// int ImgSize=(width*8)*height;//8

 memcpy(BufImg,BufImg2,ImgSize);

//======unsigned char,UINT * nWidth=======================================================

 UINT * nWidth,  UINT * nHeight
 BYTE * BufImg;
 BufImg=NULL;
 BufImg = new unsigned char [ImgSize]; //dibHi.biSizeImage

 *nHeight = NULL;
 *nWidth = NULL;

 *nHeight=height;
 *nWidth=width;


 CVisionSysView* pView =( CVisionSysView* )((CMainFrame*)AfxGetApp()->m_pMainWnd)->GetActiveView();
 CDC *pDC =pView->GetDC();
 //----------------------------------
 int rwsize = WIDTHBYTES(24*width);
 int ADDr,ADDg,ADDb;
 //----------------------------------
 int x=0; int y=0;
  for(y=0; y<height; y++)
  {
   for(x=0; x<width; x++)
   {
    ADDr=(y*rwsize)+(3*x)+2;
    ADDg=(y*rwsize)+(3*x)+1;
    ADDb=(y*rwsize)+(3*x)+0;

    *(BufImg+ADDr)=BufImg2[ADDr];  // r
    *(BufImg+ADDg)=BufImg2[ADDg];  // g
    *(BufImg+ADDb)=BufImg2[ADDb];     // b

    pDC->SetPixel(x+400,y,RGB(BufImg[ADDr],BufImg[ADDg],BufImg[ADDb]));
    //pDC->SetPixel(col,row,RGB(pixel[2],pixel[1],pixel[0]));
   }
  }


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// - 함 수  -  /////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

 int (*StepFunc_1[])(void) =
 {
  iCall_ChipTakeOff,  iCall_LaserMeasure,
  iCall_MarkRecMove,  iCall_AllMarkRec,  
  iCall_AllBadRec,  iCall_TargetMarkRec,  
  iCall_XYMovAbsorb1,  iCall_XYMovAbsorb2,
  iCall_NzlAbsorbOp1,  iCall_NzlAbsorbOp2,
  iCall_XYMountMov1,  iCall_XYMountMov2,  
  iCall_NzlMountOp1,      iCall_NzlMountOp2,
  iCall_AlignMoveXY1,     iCall_AlignMoveXY2,  
  iCall_InspectMoveXY1,   iCall_InspectMoveXY2,  
  iCall_AlignRecogOP1,    iCall_AlignRecogOP2,
  iCall_InspectRecogOP1,  iCall_InspectRecogOP2,
  iCall_NzlFocusReset1, iCall_NzlFocusReset2
 };


  if ((*StepFunc_1[index])() == NG)           // 실행 error이면
   TaskStatus1.iError = TaskStatus1.iNum;  // main분기 data
  else     // 실행성공이면
   TaskStatus1.iError = OK;

extern int  iCall_LaserMeasure(void);

/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// - 문 자  -  /////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

//8888888888888888888888888888888888888888888888888888888888888
//--------데이타 형 -----------------------------
short int, int   -2(15) ~ 2(15)-1     -32768~32767

long  int        -2(31) ~ 2(31)-1     -2147483648 ~ 2147483647

unsigned short int      0      ~2(15)-1      0 ~ 65535
unsigned int 

unsigned long int       0      ~2(32)-1      0 ~ 4294967295

float                          10(-79) ~ 10(75)

char                                         -128 ~ 127
unsigned  char                               0    ~ 255


//------------------------------------------------------
char  8
int   16
short 16
long   32
float  32
double  64
//-----------------------------------------------------
UINT-unsigned int
BYTE   -unsigned char
LPSTR  -char
(LPSTR) char*
LPTSTR   -unsigned short
LPCTSTR  -CString
//--------------------------
BOOL   A Boolean value.
BSTR   A 32-bit character pointer.
BYTE   An 8-bit integer that is not signed.
COLORREF   A 32-bit value used as a color value.
DWORD   A 32-bit unsigned integer or the address of a segment and its associated offset.
LONG   A 32-bit signed integer.
LPARAM   A 32-bit value passed as a parameter to a window procedure or callback function.
LPCSTR   A 32-bit pointer to a constant character string.
LPSTR   A 32-bit pointer to a character string.
LPCTSTR   A 32-bit pointer to a constant character string that is portable for Unicode and DBCS.
LPTSTR   A 32-bit pointer to a character string that is portable for Unicode and DBCS.
LPVOID   A 32-bit pointer to an unspecified type.
LRESULT   A 32-bit value returned from a window procedure or callback function
UINT   A 16-bit unsigned integer on Windows versions 3.0 and 3.1; a 32-bit unsigned integer on Win32.
WNDPROC   A 32-bit pointer to a window procedure.
WORD   A 16-bit unsigned integer.
WPARAM   A value passed as a parameter to a window procedure or callback function: 16 bits on Windows versions 3.0 and 3.1; 32 bits on Win32.
Data types unique to the Microsoft Foundation Class Library include the following:
POSITION   A value used to denote the position of an element in a collection; used by MFC collection classes.
LPCRECT   A 32-bit pointer to a constant (nonmodifiable) RECT structure.

//888888888888888888888888888888888888888888888888888888888888888888888888888

_CRTIMP int     __cdecl abs(int);
_CRTIMP double  __cdecl acos(double);
_CRTIMP double  __cdecl asin(double);
_CRTIMP double  __cdecl atan(double);
_CRTIMP double  __cdecl atan2(double, double);
_CRTIMP double  __cdecl cos(double);
_CRTIMP double  __cdecl cosh(double);
_CRTIMP double  __cdecl exp(double);
_CRTIMP double  __cdecl fabs(double);
_CRTIMP double  __cdecl fmod(double, double);
_CRTIMP long    __cdecl labs(long);
_CRTIMP double  __cdecl log(double);
_CRTIMP double  __cdecl log10(double);
_CRTIMP double  __cdecl pow(double, double);
_CRTIMP double  __cdecl sin(double);
_CRTIMP double  __cdecl sinh(double);
_CRTIMP double  __cdecl tan(double);
_CRTIMP double  __cdecl tanh(double);
_CRTIMP double  __cdecl sqrt(double);

  double hypot(double x,double y);직삼각형의 사변 길이
  double sqrt(double x);x의 제곱근
  double pow(double x,double y);xy. x의 y승
  double log(double x);자연 대수
  double log10(double x);상용 대수
  double exp(double x);자연 대수 exp

//=============================================================
/*---------------------- 형 변형 ----------------------------*/
//=============================================================

//---------------
double     "%.1e"
long int   "%ld"
//---------------

/*---------------------- Char 문자로 변경----------------------------*/
        DWORD dData
        char       Data[33] = "\0";
        ultoa(dData, Data, 10);
        CString    sRtn = Data;

        CString csText;
        char buff[40];
        csText=((LPCSTR)buff);


 //---메모리할당 삭제----------------------------------
 CString str;
 char *cstr=NULL;str = new char[_MAX_PATH+1];
 ::GetCurrentDirectory(_MAX_PATH+1,cstr);
 str=(LPCTSTR)(char *)cstr;
 if(cstr)delete[] cstr;
 return str;
 //-----------------------------------------------------

 char *str;
 CString Path_App =(LPCTSTR)(char *)str;
 //-----------------------------------------------------------
 (char *)(LPCTSTR)mDAT.pid,day.yy%100,day.mo,day.dd);
 //-----------------------------------------------------------


        //-----------------------------------
 (LPCTSTR)(char *)
        //-----------------------------------

/*---------------------- lstrcpy----------------------------*/
 CString m_strSend;
 BYTE temp[2000];
 lstrcpy((LPSTR)temp,(LPSTR)m_strSend.operator const char*());

/*---------------------- sprintf----------------------------*/

 char buff[100];
 int nData=100;
 sprintf(buff, "%d", nData);

/*---------------------- int--------------------------------*/
 int a=111;
 sprintf(temp,"%d",a);

 char buff[40];
 int nData;
 nData=(int)atoi((LPCSTR)buff);

 ///////////////////////////////
 short number;
 CString str;
 char buffer[20];
 if (number > 0) {
  _itoa(number,buffer,10);
  str += buffer;
 }
 str += "\r"; //CR

/*-------------------문자-> float 변경------------------------*/

 CString csTmp;
 float fHum;
 fHum = (float)atof((LPCSTR)csTmp);

*-------------------float-> 문자 변경------------------------*/
        float fData=(float) 12.345;
        CString csText;
        csText.Format("%.3f",fData);


/*-------------------문자-> long 변경------------------------------*/
 long lngBuf = ::atol(strBuf);

/*------------------- long-> 문자 변경-----------------------------*/
        long lData=1123;
 CString csTmp; csTmp.Format("%ld",lData);


*-------------------double-> 문자 변경------------------------------*/
         CString csText;
         double dData;
         csText.Format("%-13.2f",dData);

/*--------------------일정문자 삭제--------------------------------*/
 CString csRead;
  csRead.Delete(5,1);
       위치,갯수
/*------------------일정문자 추출-----------------------------------*/
 CString InString;
 CString csTemp = InString.Mid(index+1,6);
       위치 , 크기

/*------------float 반올림------------------------------------------*/
 #define Cut(A)          (float)((long int) (((A)+.05) * 10))/10;

 float Test1=(float)2.374826;
 float Test2;
 Test2=Cut(Test1);
 csTest.Format("%.6f",Test2);
 m_nisFM1LCoolRpmDecision.SetOffText(csTest);

/*------HEX and 비교구문-------------------------------------------*/
 int test1=0;
 test1 |=0x4000;
 test1 |=0x02;

 if (test1 & 0x4000)
 {
  if ((test1 & 2)==0)
  {
  AfxMessageBox("!0x02");
  }
  else
  {
  AfxMessageBox("0x02");
  }
 }
 else
 {
  AfxMessageBox("!0x4000");
 }
/*------------상위 4비트만  추출 -----------------------------------*/
 BYTE m_nInHorseTmp;
 BYTE Intemp;
 m_nInHorseTmp=0X7f;
// m_nInHorseTmp |= 0X0f;
 m_nInHorseTmp &= 0Xf0;
 Intemp=m_nInHorseTmp/16;

 m_TEST.Format("%d",Intemp);

 UpdateData(FALSE);

/*------------------------핵사값-> 십진수-------------------------*/
 int no;
 CString n,m_NoData ;
 char buf[4]; buf[0]='0';buf[1]='A';buf[2]='2';buf[3]='B';
 char data[4];
 for(int s=0; s<4; s++)
 {
 data[s] = buf[i];
 }
 no=AscHextoAscDec(data);
 n.Format("%d",no);
 m_NoData = n;
/*-----------------------AscHextoAscDec----------------------------*/
int CFileTestView::AscHextoAscDec(char hexnum[])
{
/* int dec;
 dec = (int)hex-48;
 if(dec>9)
 dec=dec-7;
 return dec;
*/
 int i=0;
 int Num[4],Sum;

 for(i=0; i<4; i++)
 {
  if(hexnum[i]>0x40)
   Num[i]=hexnum[i]-'A'+10;
  else
   Num[i]=hexnum[i]-'0';
 }
 Sum=Num[0]*16*16*16 + Num[1]*16*16 + Num[2]*16 + Num[3];

 return Sum;
}
/*---------------------- 십진수-> 핵사------------------*/
 int NUM;
 CString m_NoData;
 NUM=162;  ///핵사값=A2
 BYTE temp[3];
 temp[0] = HextoAsc(NUM/16);
 temp[1] = HextoAsc(NUM%16);
 temp[2] = '\0';
 m_NoData=temp;
/*-----------------------HextoAsc-----------------------*/
BYTE CFileTestView::HextoAsc(BYTE hexnum)
{
 unsigned char hex[] = { "0123456789ABCDEF" };
 unsigned char ascnum;
 ascnum = hex[hexnum%16];
 return ascnum;
}
/*-----------------ASC-> 정수변환-----------------------*/
 int NanBangData;
  TCHAR  NanBang[5];
  NanBang[0] = pDoc->m_RsrBuf[9];
  NanBang[1] = pDoc->m_RsrBuf[10];
  NanBang[2] = pDoc->m_RsrBuf[11];
  NanBang[3] = pDoc->m_RsrBuf[12];
  NanBang[4] = '\0';
  NanBangData  = atoi(NanBang);
/*--------------------Format----------------------------*/

 int NO[4];
 CString n;
 NO=0x31;
 n.Format("%d%d%d%d",NO[0],NO[0],NO[0],NO[0]);
 no=atoi(n);
 m_NoData = n;
 if(no==2100){m_NoData="aa";}
 else{m_NoData ="bb";}
/*--------------------- strcat---------------------------*/
 char string[80];
 char temp2[20];
    strcpy( string, "Hello world from " );
    strcat( string, "1 " );
    strcat( string, "2 " );
    strcat( string, "!" );

 sprintf(temp2,"%s\n",string);
 AfxMessageBox(temp2);

/*-----------------strok----------------------------------*/

 char seps[] = ","; char *token; char string[250];
    ///*** Establish string and get the first token:
 strcpy( string, ReadData); token = strtok(string, seps );

 char string[] = " 1 2 \n3,4,,,,,,end";
 char s

eps[]   = " ,\t\n";
 //char seps[]   = ",";
 char *token;

    ////////*** Establish string and get the first token:
    token = strtok( string, seps );
    char temp2[20];
    while( token != NULL )
    {
       //////*** While there are tokens in "string"
  sprintf(temp2,"%s",token);
  AfxMessageBox(temp2);
       ///////*** Get next token:
       token = strtok( NULL, seps );
    }


 //----------------------------------------------------
  char *data;
  char szBuf[1024];

  CString InString="OK11,123,250,125";
  sprintf(szBuf,InString);
 
  data = strtok(szBuf,",");
  AfxMessageBox(data);
 
  data = strtok(NULL,",");
  AfxMessageBox(data);

  data = strtok(NULL,",");
  AfxMessageBox(data);

  data = strtok(NULL,",");
  AfxMessageBox(data);
//------------------------------------------

 char string[] = "IMAGE1,IMAGE2,IMAGE3,IMAGE11,IMAGE4,IMAGE20";
 //char seps[]   = " ,\t\n";
 char seps[]   = ",";
 char *token;

    ////////*** Establish string and get the first token:
    token = strtok( string, seps );
    char temp2[20];
    while( token != NULL )
    {
       //////*** While there are tokens in "string"
  sprintf(temp2,"%s",token);
  AfxMessageBox(temp2);
       ///////*** Get next token:
       token = strtok( NULL, seps );
    }
/*--------------------strlen--------------------------------*/
    char temp2[20];
    char buffer[61] = "How";
    int  len;
    len = strlen( buffer );
   // sprintf(temp2,"%d",len);
    sprintf(temp2,"%s",buffer);
    AfxMessageBox(temp2);
/*---------------------- int--------------------------------*/
 int a=111;
 sprintf(temp,"%d",a);

/*------------문자 위치(길이) 결과 얻어내기------------------------------------*/

 InString="12345678+000 END";
 index = InString.Find("END");//END의 위치 값 0 ~ END 정수 값

 csText.Format("%d",index);
 AfxMessageBox(csText);

 index = InString.Find("+");
 m_csTmpString=InString.Left(index+2);//index 위치+2 까지 문자 얻음
 AfxMessageBox(m_csTmpString);


/*-----------지정 위치 문자 얻어 내기 --String.GetAt(n)--------------------------------------*/

  int Length2 =  NamBangDataBuf.GetLength();
   for(int n = 0; n < Length2; n++)
   {
   buf2[n] = NamBangDataBuf.GetAt(n);
   }
   buf2[n] = '\0';

  n 위치의 문자를 얻어냄
/*--------------------------------------------------------------
 index = InString.Find("+");//15
 while(index>=0)
 {
  m_csTmpString=InString.Left(index+2);//"+"위치 + 2 위치 문자얻음  "," 까지
  InString =InString.Right(InString.GetLength()-index-2); //전체에서 LEFT뺀 나머지 문자
  OneChar = m_csTmpString.GetAt(0);  //0  
  index = m_csTmpString.Find("N"); //4

  WAV[0] = m_csTmpString.GetAt(index-4); //V
  WAV[1]=NULL;
//  csText.Format("%d",nI);
//  AfxMessageBox(csText);
  OneChar = m_csTmpString.GetAt(index-1); //3번 위치의 "1" 얻음
  tmp[0]=OneChar;
  tmp[1]=NULL; //temp= "1";
  nI=atoi(tmp);

/*--------------------------대문자로 바꿈--------------------------------*/
 CString Buf1;
 Buf1="abcdef";
 Buf1.MakeUpper();

 AfxMessageBox(Buf1);
/*-------------------------일부 문자 뽑아 내기--------------------------*/
 CString csTmp,InString;

 InString="#SNDATAok-aa#END";

 csTmp=FindData(InString, "#SN",'#');

 AfxMessageBox(csTmp);

 결과=DATAok-aa


CString CSECSystemView::FindData(CString csData, CString csFind, TCHAR OneChar)
{
 int length,index,index2;
 CString csTmp,csTmpData;

 index = csData.Find(csFind);//MODEL_INFO
 length = csFind.GetLength();

 csTmpData=csData.Right(csData.GetLength() - index - 1);
 index2 = csTmpData.Find(OneChar);//MODEL_INFO
 csTmp = csData.Mid(length+index,index2+1-length);
// csData.Format("index=%d",index2);
 if((index < 0)||(index2 < 0)) return _T("");
 else return csTmp;
}
/*------------------------핵사값-> 십진수-------------------------*/
 int no;
 CString n,m_NoData ;
 char buf[4]; buf[0]='0';buf[1]='A';buf[2]='2';buf[3]='B';
 char data[4];
 for(int s=0; s<4; s++)
 {
 data[s] = buf[i];
 }
 no=AscHextoAscDec(data);
 n.Format("%d",no);
 m_NoData = n;

//-------------------------------------------------------------------//
BYTE CHexAscChangeView::AsctoHex(BYTE ascnum)
{
 unsigned char hex[] = { "0123456789ABCDEF" };
 unsigned char i=0;

 do
 {
  if(hex[i] == ascnum)
  {
   return i;
  }
 i++;
 }while(i<16);
 return 0;
}

/*-----------------------AscHextoAscDec----------------------------*/
int CFileTestView::AscHextoAscDec(char hexnum[])
{
/* int dec;
 dec = (int)hex-48;
 if(dec>9)
 dec=dec-7;
 return dec;
*/
 int i=0;
 int Num[4],Sum;

 for(i=0; i<4; i++)
 {
  if(hexnum[i]>0x40)
   Num[i]=hexnum[i]-'A'+10;
  else
   Num[i]=hexnum[i]-'0';
 }
 Sum=Num[0]*16*16*16 + Num[1]*16*16 + Num[2]*16 + Num[3];

 return Sum;
}
/*---------------------- 십진수-> 핵사-------------------*/
 int NUM;
 CString m_NoData;
 NUM=162;  ///핵사값=A2
 BYTE temp[3];
 temp[0] = HextoAsc(NUM/16);
 temp[1] = HextoAsc(NUM%16);
 temp[2] = '\0';
 m_NoData=temp;
/*-----------------------HextoAsc-----------------------*/
BYTE CFileTestView::HextoAsc(BYTE hexnum)
{
 unsigned char hex[] = { "0123456789ABCDEF" };
 unsigned char ascnum;
 ascnum = hex[hexnum%16];
 return ascnum;
}
/*-----------------ASC-> 정수변환-----------------------*/
 int NanBangData;
  TCHAR  NanBang[5];
  NanBang[0] = pDoc->m_RsrBuf[9];
  NanBang[1] = pDoc->m_RsrBuf[10];
  NanBang[2] = pDoc->m_RsrBuf[11];
  NanBang[3] = pDoc->m_RsrBuf[12];
  NanBang[4] = '\0';
  NanBangData  = atoi(NanBang);
/*--------------------Format----------------------------*/

 int NO[4];
 CString n;
 NO=0x31;
 n.Format("%d%d%d%d",NO[0],NO[0],NO[0],NO[0]);
 no=atoi(n);
 m_NoData = n;
 if(no==2100){m_NoData="aa";}
 else{m_NoData ="bb";}
/*--------------------- strcat---------------------------*/
 char string[80];
 char temp2[20];
    strcpy( string, "Hello world from " );
    strcat( string, "1 " );
    strcat( string, "2 " );
    strcat( string, "!" );

 sprintf(temp2,"%s\n",string);
 AfxMessageBox(temp2);

/*-----------------strok----------------------------------*/
 char string[] = " 1 2 \n3,4,,,,,,end";
 char seps[]   = " ,\t\n";
 //char seps[]   = ",";
 char *token;

   ////////*** Establish string and get the first token:
   token = strtok( string, seps );
   char temp2[20];
   while( token != NULL )
   {
      //////*** While there are tokens in "string"
  sprintf(temp2,"%s",token);
  AfxMessageBox(temp2);
      ///////*** Get next token:
      token = strtok( NULL, seps );
   }
/*--------------------strlen--------------------------------*/
   char temp2[20];
   char buffer[61] = "How";
   int  len;
   len = strlen( buffer );
  // sprintf(temp2,"%d",len);
   sprintf(temp2,"%s",buffer);
   AfxMessageBox(temp2);

Measure_r= hypot(fPoint_x,fPoint_y);
Measure_r=sqrt(fPoint_x*fPoint_x+fPoint_y*fPoint_y);

//---CString To Byte (unsigned char)------------------------------------------
 BYTE  c_str(CString str, int n)
 {
  BYTE cDt;
  int nSize=0;
  nSize=str.GetLength();
  if(nSize>=n)
  {
     cDt= str.GetAt(n);
  }
  return cDt;
 }

//------------------------------------------------------------------------------
 CString str;
 BYTE temp;
 for(int i=0; i<6; i++)
 {
  str.Format("%d : ",i);
  if(c_str(name,i)=='3')
  AfxMessageBox(str+"ok");
  else
  AfxMessageBox(str);
 }
//------------------------------------------------------------------------------
 //char 문자변형 !!!!!!!!!!!!!!!!!!!!
 BYTE temp[2];
 
 temp[0]=(c_str(name,i);
 temp[1]='\0';
 
 str=(LPSTR)temp;
 AfxMessageBox(str);
 
/*---------------------------------------------------------*/
/*----------------------HEX 8BIT  문자표현----------------------------------------*/

CString CSECKLineDVM2View::Hext8BitAsctoChange(int CheckSum)
{
 CString csHiBit,csLowBit,csResult;
 char HiBit;
 char LowBit;

 HiBit=(CheckSum & 0xf0)/16;
 LowBit=CheckSum & 0x0f;

 csHiBit=HextoAsc(HiBit);
 csLowBit=HextoAsc(LowBit);
 
 csResult=csHiBit+csLowBit;
 return csResult;
}

BYTE CModuleAgingView::HextoAsc(BYTE hexnum)
{
 unsigned char hex[] = { "0123456789ABCDEF" };
 unsigned char ascnum;
 
 int nBuf=0;

 nBuf=hexnum%16;
 if((nBuf>=0)&&(nBuf<=15))
 {
  ascnum = hex[hexnum%16];
 }
 else
 {
  ascnum =0;
 }
 return ascnum;
}
/*----------------------HEX 분할 표현----------------------------------------*/

 long  dAddress=4294967295;  //FF FF FF FF

 NAddress[3]=long((lAddress&0xff000000)>>24);
 NAddress[2]=long((lAddress&0x00ff0000)>>16);
 NAddress[1]=long((lAddress&0x0000ff00)>>8);
 NAddress[0]=long(lAddress&0x000000ff);

 unsigned char Command[]={NAddress[3],NAddress[2],NAddress[1],NAddress[0]}; //81-Command,   00 08- Data Size 8Byte
 pFrame->m_serial[PORT_MODULE_A-1].Write(Command,4);
/*----------------------HEX 232전송----------------------------------------*/

 unsigned char *BinOutImg;
 BinOutImg = NULL;     //변경전 Image file size
 BinOutImg   = new unsigned char [3*WidthLineSize*(PaletteSize_y*ImageMaxNo)];

 Data[0]=int(BinOutImg[index+0]);
 unsigned char Buf1[]={Data[0]};
 pFrame->m_serial[port-1].Write(Buf1,1);

 Data[1]=int(BinOutImg[index+1]);
 unsigned char Buf2[]={Data[1]};
 pFrame->m_serial[port-1].Write(Buf2,1);


/*----------------------String Table 얻기----------------------------------------*/
CString strTemp;
if (strTemp.LoadString(IDS_SERVERRESET))

/*----------------------한글 폰트 얻기 / 출력------------------------------------*/

const char KoreanFont_MOUM_A1[14][3] = {
 "각","간","갇","갈","감","갑","갓","강","갖","갗",
 "갘","같","갚","갛",
};
 CString csData;

 BYTE temp[3];
 temp[0] = KoreanFont_MOUM_A1[1][0];
 temp[1] = KoreanFont_MOUM_A1[1][1];
 temp[2] = '\0';

 csData=temp;
 AfxMessageBox(csData);

/*----------------------사이즈가 수시변동  끝 네자리 얻기------------------------*/

 CString strTmp=_T("");
 CString strTmp2=_T("");
 CString csData="EX-4A21";
 int nLotSize=0;

 strTmp=csData;
 
 if(strTmp.GetLength()>0)
 {
  nLotSize=strTmp.GetLength();

  if(nLotSize>=4)
  {
   for(int i=nLotSize-4; i<nLotSize; i++)
   {
   strTmp2+=strTmp.Mid(i,1);
   }
  }
 }

 if(strTmp2.GetLength()==4)
 {
 AfxMessageBox(strTmp2);
 }
/*---------------------- Delete------------------------*/
 CString csRead;
 int nNo;
 csRead.Delete(nNo,1);
//=============================================================
//=============================================================


//====입력 문자중  숫자만 체크=================================
bool AsctoHexChk(CString csNo)
{
 if(csNo=="")return false;
 int Length =  csNo.GetLength();
 if(Length<=0)return false;
 BYTE No; 
 bool chk=true;
 
 for(int i=0; i<Length; i++)
 {
  No=csNo.GetAt(i);
  if(!AsctoHex(No))chk=false;
 }
   return chk;
}

bool AsctoHex(BYTE ascnum)
{
 unsigned char hex[] = { "0123456789." };
 unsigned char i=0;
 bool Chk=false;
 do
 {
  if(hex[i] == ascnum)
  {
   Chk=true; break;
  }
  i++;
 }while(i<11);
 return Chk;
}

//====한정 문자 메세지 ==========================================
 const char BOARD1[MAX_BD][10]= {
 "DZ1","DX1","DY1","DZ2","DX2","DY2","FX1","FY1",};
 CLabelControl *pLabel;
 for(int i=0; i<MAX_BD; i++)
 {
   pLabel = (CLabelControl *)GetDlgItem(IDC_LBL_AXIS_X+i);
   pLabel->SetWindowText(LPTSTR(BOARD1[i]));
 }
 
//====리스트 사용하기============================================
typedef struct {
 CString MarkID;
 int MarkNo;
 int Registered;
 int iLight[3];
} MARKDATA_RECORD;

CList<MARKDATA_RECORD, MARKDATA_RECORD&> m_list;
void CMarkData::Load()
{
 Clear();

 MARKDATA_RECORD rec;
 CString strSection;
 CIniFile iniFile("C:\\MountData\\MarkData\\Mark.lib");
 int count = iniFile.ReadInt("Mark Library", "Count");
 for (int i=1; i<=count; i++) {
  strSection.Format("Mark #%02d", i);
  rec.MarkID = iniFile.ReadString(strSection, "Mark ID");
 
  m_list.AddTail(rec);
 }
}
void CMarkData::Save()
{
 MARKDATA_RECORD rec;
 POSITION pos;
 CString strSection;
 int count = GetCount();
 CIniFile iniFile("C:\\MountData\\MarkData\\Mark.lib");
 iniFile.WriteInt("Mark Library", "Count", count);
 for (int i=0; i<count; i++) {
  pos = m_list.FindIndex(i);
  rec = m_list.GetAt(pos);
  iniFile.WriteDouble(strSection, "OuterDiameter", rec.OuterDiameter);
 }
}
void CMarkData::Clear()
{
 m_list.RemoveAll();
}
MARKDATA_RECORD CMarkData::GetData(int index)
{
 ASSERT(index > 0 && index <= m_list.GetCount());
 POSITION pos = m_list.FindIndex(index-1);
 MARKDATA_RECORD rec = m_list.GetAt(pos);
 return rec;
}
bool CMarkData::InsertBlankData(int index)
{
 ASSERT(index > 0 && index <= m_list.GetCount()+1);
 MARKDATA_RECORD rec;
 rec.MarkID.Empty();
 rec.MarkNo = 0;
 rec.Registered = 0;
 rec.iLight[0] = 1;
 rec.iLight[1] = 1;
 rec.iLight[2] = 1;
 if (index > m_list.GetCount()) {
  m_list.AddTail(rec);
 }
 else {
  POSITION pos = m_list.FindIndex(index-1);
  m_list.InsertBefore(pos, rec);
 }
 return true;
}

//___________________________________________________________________________

void CMarkData::DeleteData(int index)
{
 if (index < 0 || index > m_list.GetCount()) return;
 POSITION pos = m_list.FindIndex(index-1);
 m_list.RemoveAt(pos);
}
//===========================================================================
//===========================================================================

void CMarkData::SetData(int index, MARKDATA_RECORD rec)
{
 ASSERT(index > 0 && index <= m_list.GetCount());
 POSITION pos = m_list.FindIndex(index-1);
 m_list.SetAt(pos, rec);
}

//====struct=================================================================

//typedef struct tagBLOBDATA { short ltx, lty, rbx, rby; int n, pc; float cx, cy, r, g, b, u02, u20, u11, m, v; } BLOBDATA;

//---------------------------------------------------------------------------
//====Point Reutn============================================================
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

BYTE * BMPFile::LoadBMP(CString fileName,UINT *width, UINT *height)
{
 BYTE *outBuf=NULL;
 long bufsize = (long)w * 3 * (long)h;
 outBuf=(BYTE *) new BYTE [bufsize];


 for (int col=0;col<w;col++)
 {
  long offset = col * 3;
  char pixel[3];
  if (fread((void  *)(pixel),1,3,fp)==3)
  {
  // we swap red and blue here
  *(outBuf + rowOffset + offset + 0)=pixel[2];  // r
  *(outBuf + rowOffset + offset + 1)=pixel[1];  // g
  *(outBuf + rowOffset + offset + 2)=pixel[0];  // b
  }
 }

 int w;
 int h;
 *width=w;
 *height=h;
 return outBuf;
}

//===========================================================================
BYTE * BMPFile::LoadBMP(CString fileName,
      UINT *width,
      UINT *height)
{
    BITMAP inBM;

    BYTE m1,m2;
    long filesize;
    short res1,res2;
    long pixoff;
    long bmisize;                   
    long compression;
    unsigned long sizeimage;
    long xscale, yscale;
    long colors;
    long impcol;
   

 BYTE *outBuf=NULL;
 
 // for safety
 *width=0; *height=0;

 // init
 m_errorText="OK";
 m_bytesRead=0;

 FILE *fp;
 
 fp=fopen(fileName,"rb");
 if (fp==NULL) {
  CString msg;                   
  msg="Can't open file for reading :\n"+fileName;
  m_errorText=msg;
  return NULL;
 } else {
     long rc;
  rc=fread((BYTE  *)&(m1),1,1,fp); m_bytesRead+=1;
  if (rc==-1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((BYTE  *)&(m2),1,1,fp); m_bytesRead+=1;
  if (rc==-1) m_errorText="Read Error!";
  if ((m1!='B') || (m2!='M')) {
   m_errorText="Not a valid BMP File";
   fclose(fp);
   return NULL;
        }
       
  ////////////////////////////////////////////////////////////////////////////
  //
  // read a ton of header stuff

  rc=fread((long  *)&(filesize),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((int  *)&(res1),2,1,fp); m_bytesRead+=2;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((int  *)&(res2),2,1,fp); m_bytesRead+=2;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(pixoff),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(bmisize),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(inBM.bmWidth),4,1,fp);  m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(inBM.bmHeight),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((int  *)&(inBM.bmPlanes),2,1,fp); m_bytesRead+=2;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((int  *)&(inBM.bmBitsPixel),2,1,fp); m_bytesRead+=2;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(compression),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(sizeimage),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(xscale),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(yscale),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(colors),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  rc=fread((long  *)&(impcol),4,1,fp); m_bytesRead+=4;
  if (rc!=1) {m_errorText="Read Error!"; fclose(fp); return NULL;}

  ////////////////////////////////////////////////////////////////////////////
  // i don't do RLE files

  if (compression!=BI_RGB) {
      m_errorText="This is a compressed file.";
      fclose(fp);
      return NULL;
     }

  if (colors == 0) {
   colors = 1 << inBM.bmBitsPixel;
  }


  ////////////////////////////////////////////////////////////////////////////
  // read colormap

  RGBQUAD *colormap = NULL;

  switch (inBM.bmBitsPixel) {
  case 24:
   break;
   // read pallete
  case 1:
  case 4:
  case 8:
   colormap = new RGBQUAD[colors];
   if (colormap==NULL) {
    fclose(fp);
    m_errorText="Out of memory";
    return NULL;
   }

   int i;
   for (i=0;i<colors;i++) {
    BYTE r,g,b, dummy;

    rc=fread((BYTE *)&(b),1,1,fp);
    m_bytesRead++;
    if (rc!=1) {
     m_errorText="Read Error!";
     delete [] colormap;
     fclose(fp);
     return NULL;
    }

    rc=fread((BYTE  *)&(g),1,1,fp);
    m_bytesRead++;
    if (rc!=1) {
     m_errorText="Read Error!";
     delete [] colormap;
     fclose(fp);
     return NULL;
    }

    rc=fread((BYTE  *)&(r),1,1,fp);
    m_bytesRead++;
    if (rc!=1) {
     m_errorText="Read Error!";
     delete [] colormap;
     fclose(fp);
     return NULL;
    }


    rc=fread((BYTE  *)&(dummy),1,1,fp);
    m_bytesRead++;
    if (rc!=1) {
     m_errorText="Read Error!";
     delete [] colormap;
     fclose(fp);
     return NULL;
    }

    colormap[i].rgbRed=r;
    colormap[i].rgbGreen=g;
    colormap[i].rgbBlue=b;
   }
   break;
  }


  if ((long)m_bytesRead>pixoff) {
   fclose(fp);
   m_errorText="Corrupt palette";
   delete [] colormap;
   fclose(fp);
   return NULL;
  }

  while ((long)m_bytesRead<pixoff) {
   char dummy;
   fread(&dummy,1,1,fp);
   m_bytesRead++;
  }

  int w=inBM.bmWidth;
  int h=inBM.bmHeight;

  // set the output params
  *width=w;
  *height=h;

  long row_size = w * 3;

  long bufsize = (long)w * 3 * (long)h;

  ////////////////////////////////////////////////////////////////////////////
  // alloc our buffer

  outBuf=(BYTE *) new BYTE [bufsize];
  if (outBuf==NULL) {
   m_errorText="Memory alloc Failed";
  } else {

   ////////////////////////////////////////////////////////////////////////////
   // read it

   long row=0;
   long rowOffset=0;

   // read rows in reverse order
   for (row=inBM.bmHeight-1;row>=0;row--) {

    // which row are we working on?
    rowOffset=(long unsigned)row*row_size;           

    if (inBM.bmBitsPixel==24) {

     for (int col=0;col<w;col++) {
      long offset = col * 3;
      char pixel[3];

      if (fread((void  *)(pixel),1,3,fp)==3) {
       // we swap red and blue here
       *(outBuf + rowOffset + offset + 0)=pixel[2];  // r
       *(outBuf + rowOffset + offset + 1)=pixel[1];  // g
       *(outBuf + rowOffset + offset + 2)=pixel[0];  // b
      }

     }

     m_bytesRead+=row_size;
     
     // read DWORD padding
     while ((m_bytesRead-pixoff)&3) {
      char dummy;
      if (fread(&dummy,1,1,fp)!=1) {
       m_errorText="Read Error";
       delete [] outBuf;
       fclose(fp);
       return NULL;
      }

      m_bytesRead++;
     }
 
     
    } else { // 1, 4, or 8 bit image

     ////////////////////////////////////////////////////////////////
     // pixels are packed as 1 , 4 or 8 bit vals. need to unpack them

     int bit_count = 0;
     UINT mask = (1 << inBM.bmBitsPixel) - 1;

     BYTE inbyte=0;

     for (int col=0;col<w;col++) {
     
      int pix=0;

      // if we need another byte
      if (bit_count <= 0) {
       bit_count = 8;
       if (fread(&inbyte,1,1,fp)!=1) {
        m_errorText="Read Error";
        delete [] outBuf;
        delete [] colormap;
        fclose(fp);
        return NULL;
       }
       m_bytesRead++;
      }

      // keep track of where we are in the bytes
      bit_count -= inBM.bmBitsPixel;
      pix = ( inbyte >> bit_count) & mask;

      // lookup the color from the colormap - stuff it in our buffer
      // swap red and blue
      *(outBuf + rowOffset + col * 3 + 2) = colormap[pix].rgbBlue;
      *(outBuf + rowOffset + col * 3 + 1) = colormap[pix].rgbGreen;
      *(outBuf + rowOffset + col * 3 + 0) = colormap[pix].rgbRed;
     }

     // read DWORD padding
     while ((m_bytesRead-pixoff)&3) {
      char dummy;
      if (fread(&dummy,1,1,fp)!=1) {
       m_errorText="Read Error";
       delete [] outBuf;
       if (colormap)
        delete [] colormap;
       fclose(fp);
       return NULL;
      }
      m_bytesRead++;
     }
    }
   }
 
  }

  if (colormap) {
   delete [] colormap;
  }

  fclose(fp);

    }

 return outBuf;
}
//=================================================================================================================

BYTE* CMemFile::Alloc(DWORD nBytes)
{
 return (BYTE*)malloc((UINT)nBytes);
}

BYTE *buf = JpegFile::JpegFileToRGB(....);
delete [] buf;

BYTE * JpegFile::JpegFileToRGB(CString fileName, UINT *width,  UINT *height)
{
 *width=0;
 *height=0;

 BYTE *dataBuf;
 dataBuf=(BYTE *)new BYTE[width * 3 * height];
 if (dataBuf==NULL) {
  return NULL;
 }

 return dataBuf;

}

BYTE * JpegFile::MakeDwordAlignedBuf(BYTE *dataBuf,UINT widthPix,UINT height, UINT *uiOutWidthBytes)
{
 ////////////////////////////////////////////////////////////
 // what's going on here? this certainly means trouble
 if (dataBuf==NULL)return NULL;

 ////////////////////////////////////////////////////////////
 // how big is the smallest DWORD-aligned buffer that we can use?
 UINT uiWidthBytes;
 uiWidthBytes = WIDTHBYTES(widthPix * 24);

 DWORD dwNewsize=(DWORD)((DWORD)uiWidthBytes * (DWORD)height);
 BYTE *pNew;

 ////////////////////////////////////////////////////////////
 // alloc and open our new buffer
 pNew=(BYTE *)new BYTE[dwNewsize];
 if (pNew==NULL) {
  return NULL;
 }
 
 ////////////////////////////////////////////////////////////
 // copy row-by-row
 UINT uiInWidthBytes = widthPix * 3;
 UINT uiCount;
 for (uiCount=0;uiCount < height;uiCount++) {
  BYTE * bpInAdd;
  BYTE * bpOutAdd;
  ULONG lInOff;
  ULONG lOutOff;

  lInOff=uiInWidthBytes * uiCount;
  lOutOff=uiWidthBytes * uiCount;

  bpInAdd= dataBuf + lInOff;
  bpOutAdd= pNew + lOutOff;

  memcpy(bpOutAdd,bpInAdd,uiInWidthBytes);
 }

 *uiOutWidthBytes=uiWidthBytes;
 return pNew;
}

BOOL JpegFile::VertFlipBuf(BYTE  * inbuf,
        UINT widthBytes,
        UINT height)
{  
 BYTE  *tb1;
 BYTE  *tb2;

 if (inbuf==NULL)
  return FALSE;

 UINT bufsize;

 bufsize=widthBytes;

 tb1= (BYTE *)new BYTE[bufsize];
 if (tb1==NULL) {
  return FALSE;
 }

 tb2= (BYTE *)new BYTE [bufsize];
 if (tb2==NULL) {
  delete [] tb1;
  return FALSE;
 }
 
 UINT row_cnt;    
 ULONG off1=0;
 ULONG off2=0;

 for (row_cnt=0;row_cnt<(height+1)/2;row_cnt++) {
  off1=row_cnt*bufsize;
  off2=((height-1)-row_cnt)*bufsize;  
 
  memcpy(tb1,inbuf+off1,bufsize);
  memcpy(tb2,inbuf+off2,bufsize);
  memcpy(inbuf+off1,tb2,bufsize);
  memcpy(inbuf+off2,tb1,bufsize);
 }

 delete [] tb1;
 delete [] tb2;

 return TRUE;
}       

BOOL JpegFile::MakeGrayScale(BYTE *buf, UINT widthPix, UINT height)
{
 if (buf==NULL)
  return FALSE;

 UINT row,col;
 for (row=0;row<height;row++) {
  for (col=0;col<widthPix;col++) {
   LPBYTE pRed, pGrn, pBlu;
   pRed = buf + row * widthPix * 3 + col * 3;
   pGrn = buf + row * widthPix * 3 + col * 3 + 1;
   pBlu = buf + row * widthPix * 3 + col * 3 + 2;

   // luminance
   int lum = (int)(.299 * (double)(*pRed) + .587 * (double)(*pGrn) + .114 * (double)(*pBlu));

   *pRed = (BYTE)lum;
   *pGrn = (BYTE)lum;
   *pBlu = (BYTE)lum;
  }
 }
 return TRUE;
}

//============================================================================

//--------Bit 구하기- -----------------------------

typedef struct {
 unsigned b0 : 1, b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1;
} byte_bits;

typedef union {
 BYTE bByte;
 byte_bits bit;
} lsByte;


lsByte bUnivIO;

 bUnivIO=(UINT8)250;

#include "Led.h"
CLed m_LedOut0;
DDX_Control(pDX, IDC_LED_OUT0, m_LedOut0);

 m_LedOut0.SetStatus( bUnivIO.bit.b0 );
 m_LedOut1.SetStatus( bUnivIO.bit.b1 );
 m_LedOut2.SetStatus( bUnivIO.bit.b2 );
 m_LedOut3.SetStatus( bUnivIO.bit.b3 );
 m_LedIn0.SetStatus( bUnivIO.bit.b4 );
 m_LedIn1.SetStatus( bUnivIO.bit.b5 );
 m_LedIn2.SetStatus( bUnivIO.bit.b6 );
 m_LedIn3.SetStatus( bUnivIO.bit.b7 );


 
int CUDPSock::SendTo(const void* lpBuf, int nBufLen, LPCTSTR lpszHostAddress, int nFlags)
{
 sockaddr_in Addr;
 memset((char *)&Addr, 0x00, sizeof(Addr));
 Addr.sin_family = AF_INET;
 Addr.sin_addr.s_addr = inet_addr(lpszHostAddress);
 Addr.sin_port = htons(m_iPort);//서버,클라이언트중 port지정한 UDP port로 송수신(내부서버에지정)

 char *buf = NULL;
 int iSize = lstrlen((char*)lpBuf);

 buf = (char*)malloc(iSize);

 memcpy(buf,lpBuf,iSize);
 
 //CUDPSock::DATAPACKET DataPacket;
 //memcpy(DataPacket.szData, (char*)lpBuf, nBufLen);
 //DataPacket.SetCheck();
 //int iResult = sendto(m_Sock, (char*)&DataPacket, sizeof(CUDPSock::DATAPACKET), nFlags, (const struct sockaddr *)&Addr, sizeof(Addr));
 int iResult = sendto(m_Sock, buf, iSize, nFlags, (const struct sockaddr *)&Addr, sizeof(Addr));
 return 0;
}
//---------------------------------------------------------------------------
        //-----특정 문자 바꾸기 -----------------------------------
 CString PathName.Replace( "\\", "/" );


 //-----확장자 바꾸기---------------------------------------
 CString ChangeFileExt(CString csFile, CString csExe)
 {
 CString str;
 int Index=0;
 char *token;
 char szBuf[1024];
 char temp2[100];
 char seps[]   = "\\";
    ////////*** Establish string and get the first token:

 if(csFile.GetLength()>3)printf(szBuf,csFile); else return "";
 CString csGetData="";
 sprintf(szBuf,csFile);
 token = strtok(szBuf,seps);

    while( token != NULL )
    {
       //////*** While there are tokens in "string"
  sprintf(temp2,"%s",token);
  csGetData=temp2;
       ///////*** Get next token:
     token = strtok( NULL, seps );
    }

 int index=0;
 if(csGetData.GetLength()>1)index = csGetData.Find("."); else return "";
 CString csData="";
 csData=csGetData.Mid(0,index);// AfxMessageBox(csData);

 str=csData+csExe;
 return str;
 }

 //----------------------------------------------------------
 CString NewFileName;
 char sSource[256]
 //찾고자 하는것, 바꾸고자 하는것을 받는다.
 strcpy( sSource, m_FileNameBefore.operator LPCTSTR() );
 //----------------------------------------------------------

 unsigned char *temp = NULL;
 temp = new unsigned char [Length];

 CString Filename=="C:\\Polaronix\\Back\\Ch01\\*.*";
 //-------------------
 LPSTR temp = Filename.GetBuffer(Filename.GetLength()*2);  //*char
   
 //-------------------
 char temp[50];
 for(i=0; i<50; i++) temp[i]='\0';
 lstrcpy((LPSTR)temp,(LPSTR)Filename.operator const char*());

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

 char temp[50];
 int Length =  Filename.GetLength();
   //for(i=0; i<50; i++) temp[i]='\0';
 for(i = 0; i < Length; i++)
 {
     temp[i] = Filename.GetAt(i);
 }
 temp[i]= '\0';

 AfxMessageBox(temp);

 unsigned char Buf1[]={Data[0]};
 pFrame->m_serial[port-1].Write(Buf1,1);

//-----------------------------------------------------------------------------------
//------숫자 감소--------------------------------------------------------------------
 for (i = 255; i > 0; i--)
//-----------------------------------------------------------------------------------
//--unsigned char-> CString ,  unsigned char-> char----------------------------------
//-----------------------------------------------------------------------------------

 int Length=255;
 unsigned char *temp = NULL;
 temp = new unsigned char [Length];

 char temp2[2]; CString csText;
// m_ccEdit1.GetWindowText((LPSTR)temp,255);

 for(int i=0; i<Length; i++)
 {
  temp2[0]=temp[i]; temp2[1]='\0';
  csText+=(LPSTR)temp2;
 }

 AfxMessageBox(csText);


//-----------------------------------------------------------------------------------
//------숫자 추출--------------------------------------------------------------------

  100자리
  hundred= (int)(Sum/ 100);
  ten= (Sum-(hundred*100))/10;
  one=Sum-((hundred*100)+(ten*10));


  1000자리
  thousand= =(int)(Sum/ 1000);              
  hundred= (int)(Sum-(thousand*1000))/100;
  ten= (Sum-((thousand*1000)+(hundred*100)))/10;
  one=Sum-(int)((thousand*1000)+(hundred*100)+(ten*10));

  10000자리
  tenthousand =(int)(Sum/ 10000);              
  thousand=  (int)(Sum-(tenthousand*10000))/1000;
  hundred= (int)(Sum-((tenthousand*10000)+(thousand*1000)+(hundred*100)))/100;
  ten= (Sum-((tenthousand*10000)+(thousand*1000)+(hundred*100)))/10;
  one=Sum-(int)((tenthousand*10000)+(thousand*1000)+(hundred*100)+(ten*10));

//---char-> CString------------------------------------
 char temp[255];
 for(int i=0; i<255; i++) temp[i]='\0';

 CString csText=(LPSTR)temp;
 AfxMessageBox(csText);

//---------------*.* 삭제 처리-------------------------------------------------*/

  CString Filename="C:\\Polaronix\\Back\\Ch01\\*.*";
  int Length =  Filename.GetLength();
  char temp[50];

  for(i=0; i<50; i++) temp[i]='\0';
  lstrcpy((LPSTR)temp,(LPSTR)Filename.operator const char*());

  SHFILEOPSTRUCT sfo;
  memset(&sfo,0,sizeof(sfo));
  sfo.wFunc = FO_DELETE;
  sfo.fFlags =OFN_SHOWHELP; //메시지 창 뛰우지 않음

  sfo.pFrom=(LPSTR)temp;
  SHFileOperation(&sfo);

/*  for(i = 0; i < 20; i++)
  {
     csTmp.Format("%d",temp[i]);  AfxMessageBox(csTmp);
  }
*/

/*------% 계산------------------------------------------------------------*/
 //-------------------------------------------
 //-------------------------------------------

 0-255 에 대한 100%

 // 수량에 대한 % 계산  x(%)
 // 255 : 100(%) = 25 : x(%)    (25의  %)
 // x(%) = (value/255)*100
 int value=25;
 float fData=float(value)/255;fData=float(fData*100);if(fData<0)fData=0;     


 // %에 대한 수량 구하기  x(no)
 // 255 : 100(%) = x :10(%)    (10%에 대한 값)
 // x=(10/100)*255 

 //int value=10;
 //float fData=float(value/100);fData=float(fData*255);if(fData<0)fData=0;


 fData=float(fData)/100;fData=float(fData*255);      //Limit값
 fData=Cut(fData); m_threshMin=int(fData);
 //-------------------------------------------
 //-------------------------------------------
 
 float nData1=0;int nData2=0;

// nData1=nImageTotalSize-(nAddressCount*256);
 nData1=nImageTotalSize-nAddressCount;
 
 nData2=int((nData1/nImageTotalSize)*100);
 nPercent=int(100-nData2);


 strText.Format("Image Download: %d/100",nPercent);//Pallete X Size
 SetDlgItemText(IDC_IMAGEDOWNLOADSTATIC_A, strText);
 
 if((nPercent>=0)&&(nPercent<=100))
 m_ccModuleAdownloadProgress.SetPos(nPercent);
/*-----------------------------------------------------------------------*/

BOOL AFXAPI AfxVerifyLicFile(HINSTANCE hInstance, LPCTSTR pszLicFileName,
 LPCOLESTR pszLicFileContents, UINT cch)
{
 // Assume the worst...
 BOOL bVerified = FALSE;

 // Look for license file in same directory as this DLL.
 TCHAR szPathName[_MAX_PATH];
 ::GetModuleFileName(hInstance, szPathName, _MAX_PATH);
 LPTSTR pszFileName = _tcsrchr(szPathName, '\') + 1;
 lstrcpy(pszFileName, pszLicFileName);

 #ifndef OLE2ANSI
 LPSTR pszKey = NULL;
 #endif
 LPBYTE pbContent = NULL;

 TRY
 {
  // Open file, read content and compare.

  CFile file(szPathName, CFile::modeRead);

  if (cch == -1)
 #ifdef OLE2ANSI
   cch = lstrlen(pszLicFileContents);
 #else
   cch = wcslen(pszLicFileContents);

  pszKey = (char*)_alloca(cch*2 + 1);
  cch = _wcstombsz(pszKey, pszLicFileContents, cch*2 + 1);
 #endif

  if (cch != 0)
  {
   --cch;  // license file won't contain the terminating null char
   pbContent = (BYTE*)_alloca(cch);
   file.Read(pbContent, cch);

 #ifndef OLE2ANSI
   if (memcmp(pszKey, pbContent, (size_t)cch) == 0)
 #else
   if (memcmp(pszLicFileContents, pbContent, (size_t)cch) == 0)
 #endif
    bVerified = TRUE;
  }
 }
 END_TRY

 return bVerified;
}

/*---------------------Hex -> CString------------------------------------------------------*/
void CTestView::OnButton1()
{
 // TODO: Add your control notification handler code here
 CString csTmp="";
 char hexnum=0x7f; //BYTE hexnum=0x01;

 csTmp=HextoAsctoString(hexnum);
 AfxMessageBox(csTmp);
}

CString CTestView::HextoAsctoString(BYTE hexnum)
{
 CString csTmp="0";
 unsigned char hex[] = { "0123456789ABCDEF" };

 BYTE num;
 BYTE temp[3];

 num=hexnum/16;
 temp[0] = hex[num%16];

 num=hexnum%16;
 temp[1] =hex[num%16];
 
 temp[2] = '\0';
 csTmp=temp;

 return csTmp;
}

/*---------------------CString 한줄씩 얻기        ----------------------------------*/
//-----------------------------------------------------------------------------------

 //----한줄 얻기--------------------------------
 CString csData="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";

 int MaxRow = MAXROW_TIME+1;
 int MaxCol = MAXCOL_TIME;
 CString csTmp="";

 int nGetCol=1;
 if(nMode==MODE_ONTIME)nGetCol=1;if(nMode==MODE_OFFTIME)nGetCol=2;

 int nListMaxCount=0;CString csGetData[MAXROW_TIME];
 LPTSTR pstr;LPTSTR pstrToken;
 TCHAR seps[] =_T(",");
 pstr=csData.GetBuffer(0);
 pstrToken=_tcstok(pstr,seps);

 while(pstrToken !=NULL)
 {
  if(nListMaxCount<MaxRow){csGetData[nListMaxCount]=pstrToken;AfxMessageBox(csGetData[nListMaxCount],MB_OK);}
  pstrToken=_tcstok(NULL,seps);
  nListMaxCount++;
 }
 csData.ReleaseBuffer(-1);


 //----여러 줄 얻기------------------------------------

// CString str =_T("First\tSecond Third,Fourth\t Fifth");
 CString str =_T("100,200,\n300,45.0\n");
// CString str= m_csTestFileData[0];
 CString csdata="";
 int nListMaxCount=0;
 LPTSTR pstr;
 LPTSTR pstrToken;
// TCHAR seps[] =_T("\t, ");
 TCHAR seps[] =_T("\n");
 
 pstr=str.GetBuffer(0);

 pstrToken=_tcstok(pstr,seps);

 while(pstrToken !=NULL)
 {
 // AfxMessageBox(pstrToken,MB_OK);
  pstrToken=_tcstok(NULL,seps);

   if(pstrToken!=NULL)
   {
     char seps[] = ","; char *token; char string[250];
          ///*** Establish string and get the first token:
     strcpy( string, pstrToken); token = strtok(string, seps );
     csdata="";csdata=token;
     // Data-0
     AfxMessageBox(csdata);
         
     int nCount=0;
       while( token != NULL )
       {
         token = strtok( NULL, seps );
      csdata="";csdata=token;
      //Data-1
      if(nCount==0)
      AfxMessageBox(csdata);
      csdata="";csdata=token;//csdata=csdata+"\n";
      //Data-2
      if(nCount==1)
      AfxMessageBox(csdata);
      nCount++;
       }
     nListMaxCount++;
   }
 }
 str.ReleaseBuffer(-1);
 AfxMessageBox(pstr, MB_OK);

//------------@(0x40) MASK-----------------------------------------------------------------
         //MASK 0100 0000 0x40
  //100  0000 0000  0110 0100  (0100 0000) (0100 0000) (0100 0110) (0100 0100)   @@FD  
  //12300   0011 0000  0000 1100     (0100 0011) (0100 0000) (0100 0000) (0100 1100)   C@@L
//-----------------------------------------------------------------------------------------

/*---------------------일정간격의 Board 번호와 Ch 번호 구하기 ----------------------------------*/

  int nBoardNo=0;
  int nChNo=0;
  int nMax= CHMAX/12;
  int nChMax=12;
  CString csTmp="";
 
   if(m_nTestSendCh<nChMax){nChNo=m_nTestSendCh;} //0-11 12ch
   else
   {
    for(int i=1; i<nMax; i++)
    {
    nBoardNo=m_nTestSendCh/(12*i);
    if(nBoardNo<12)break;
    }
    nChNo=m_nTestSendCh-(12*nBoardNo);
   }
 
   csTmp.Format("No%d, nBoard%d, Ch%d",m_nTestSendCh,nBoardNo,nChNo);
   AfxMessageBox(csTmp);

   m_nTestSendCh++;


/*----------------------반올림 -----------------------------------------------*/

#define Cut(A)          (float)((long int) (((A)+.05) * 10))/10;
#define Cut2(A)          (float)((long int) (((A)+.5) * 10))/10;


/*----------------------퍼센트 구하기 ----------------------------------------*/
 
 // 100 : 80(환산 기준치)
 // 퍼센트 50 구하기
 // (50/100)*80
 // (50*0.01)*80

 int nPercent=(m_ccChModel[nCh].m_SCROLLPERCENT*0.01)*m_ccChModel[nCh].m_PALETTE_SIZE_X;

 100퍼센트

 (측정값/기준값)*100
 

/*--------------------------------------------------------------------------------*/

 char temp[80];
 lstrcpy((LPSTR)temp,(LPSTR)pDlg->m_strIp.operator const char*());
 //-------------------------------------------------------------//

 BYTE temp[200];
 CString csText="[0](@@,0B)";
 lstrcpy((LPSTR)temp,(LPSTR)csText.operator const char*());
 //클라이언트에 보낸다.
 m_pClientSock->Send(temp,200);


 CString csText;
 char buff[40];
 csText=((LPCSTR)buff);


 const char Error_message[4][40] = {
 "Comm Data Receive Error      ",
 "Image Download Error         ",
 "MPU Control Error            ",
 "Comm Error        ",
};


/*---------------------- COleDateTime------------------------*/
 CString csWorkTime;
 COleDateTime ccTestTime;
 ccTestTime=COleDateTime::GetCurrentTime();
 csWorkTime=ccTestTime.Format("%I:%M:%S %p");
     ccTestTime.Format("%Y %m %d %H:%M");
//--
 COleDateTime tmpDateTime = COleDateTime::GetCurrentTime();
 String strTime;

 strTime.Format("%4d.%02d.%02d/%02d:%02d:%02d",
 tmpDateTime.GetYear(), tmpDateTime.GetMonth(),tmpDateTime.GetDay(),
 tmpDateTime.GetHour(),tmpDateTime.GetMinute(), tmpDateTime.GetSecond());
//--
 CString strTime;
 COleDateTime tmpDateTime = COleDateTime::GetCurrentTime();
 strTime.Format("%4d_%02d_%02d_%02d_%02d_%02d_Err.txt",
 tmpDateTime.GetYear(), tmpDateTime.GetMonth(),tmpDateTime.GetDay(),
 tmpDateTime.GetHour(),tmpDateTime.GetMinute(), tmpDateTime.GetSecond());
 m_csErrorFileName=strTime;

//-------------------------------------------------------------------------------------------
 int MaxRow = MAXRAW+1;
 int MaxCol = MAXCOL;
 CString cs=""; CString csTmp="";
 int col=3;

 if(m_bSendAllCheck){m_bSendAllCheck=FALSE; cs="OK";}
 else{m_bSendAllCheck=TRUE;cs="-";}
 for (int row = 1; row < MaxRow; row++) {

  csTmp=m_GridCtrl.GetItemText(row, 1);
  if(csTmp!="")
  {
   m_GridCtrl.SetItemFormat(row, col, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
   m_GridCtrl.SetItemText(row, col, cs);
  }
 }
 m_GridCtrl.Invalidate();
//--------------------------------------------------------------------------------------------
BOOL CXYSystemView::FileDataUpdate_RGB_Percent()
{
 __int16   length, exist;
 char   str[200];
 int index=0;
 int nListMaxCount=0;

 FILE   *fp ;
 CString   filename=_T("");
 CString   ReadData=_T("");
 CString   strTmp=_T("");  
 CString data=_T("");
 BOOL   bFileCheck=false;
 BOOL   bFileCheck2=false;

 filename = CSRGBPercentFileName;
 exist = access(filename,0);  

 if (!exist && (fp = fopen(filename,"rt")) != NULL) {
  while (!feof(fp)) {
   ReadData.Empty();
   if ( fgets(str, 200, fp) != NULL) {   // error Return NULL
    ReadData.Format("%s", str);
    length = ReadData.GetLength();

    if(bFileCheck2==false)//처움에만 찾기
    {
    index = ReadData.Find("#SETUP$");
    if(index>=0){bFileCheck=true; index=0; }
    else{AfxMessageBox("Save Data Not Find!"); break;}
    }

    index = ReadData.Find("\t");
    if(index>=0)
    {
    ReadData.Format("%s", ReadData.Mid(0 , length-2));
    }
    else
    {
    ReadData.Format("%s", ReadData.Mid(0 , length-1));
    }
 
    if(ReadData=="#ENDEQ$"){break;}

    if(bFileCheck)
    {
     if(bFileCheck2)
     {
      if(nListMaxCount>=CHMAX){AfxMessageBox("Posion X Save File Error!!");break;}
     
      if(ReadData!="")
      {
      // char seps[]   = " ,\t\n";
       char seps[]   = ",";
       char *token;
       char string[250];
         ////////*** Establish string and get the first token:
       strcpy( string, ReadData);
         token = strtok(string, seps );
           int nCount=0;
         while( token != NULL )
         {
           ///////*** Get next token:
          token = strtok( NULL, seps );
        if(nCount==0)
        FRGB_Percent_R[nListMaxCount]=atof(token);
        if(nCount==1)
        FRGB_Percent_G[nListMaxCount]=atof(token);
        if(nCount==2)
        FRGB_Percent_B[nListMaxCount]=atof(token);
        if(nCount==3)
        FRGB_Percent_Gray[nListMaxCount]=atof(token);

        nCount++;
         }
       nListMaxCount++;
      }
     }
    }
       bFileCheck2=true;//처움에만 찾기
   }
  }
 /// fclose(fp);
 } else {
 // SendDlgItemMessage(IDC_STATIC_WLREM, WM_SETTEXT,0,(LPARAM)(LPSTR)"DATA NONE");
 // AfxMessageBox("File Data Not Find! "+CSCHRunTimeFileName);
  FileDataSave_RGB_Percent();
  return FALSE;
 }
 fclose(fp);return TRUE;
}

//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// 화일 디렉토리중 화일명만 추출하기
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
CString  FileNameGet_token(CString csRead)
{
 char *token;
 char szBuf[1024];
 char seps[]   = "\\";
   ////////*** Establish string and get the first token:
 //CString InString="C:\\DMX\\Bmp\\Field_R.bmp";
 CString InString=csRead;
 if(InString.GetLength()==0)return "";
 sprintf(szBuf,InString);
 
 CString csGetData="";
 token = strtok(szBuf,seps);

    char temp2[20]; int Index=0;
    while( token != NULL )
    {
       //////*** While there are tokens in "string"
  sprintf(temp2,"%s",token);
  csGetData=temp2;
       ///////*** Get next token:
     token = strtok( NULL, seps );
    }

 int index=0;
 if(csGetData.GetLength()>0)index = csGetData.Find("."); else return "";
 CString csData="";
 csData=csGetData.Mid(0,index); //AfxMessageBox(csData);
 return csData;
}
//---------------------------------------------------------------------------------

/*-------------십진수값  자리분할 각각의 해당 자리수 버퍼에 저장----------------*/

 //------------------------------------------
  if(Sum>0)
   {
    hundred= (int)(Sum/ 100);
    ten= (Sum-(hundred*100))/10;
    one=Sum-((hundred*100)+(ten*10));
   }  
        //------------------------------------------

 int i,Sum,thousand,hundred,ten,one,Count;
 Sum=thousand=hundred=ten=one=Count=0;
 
 char Rpm[4];
 char RpmBuf[4];

 for(i=0; i<4; i++)
 {
 Rpm[i]=0;
 RpmBuf[i]=0;
 }

 Sum=6234;
 
 for(i=0; i<Sum; i++)
 {  
  Count++;
  if(Count==10)
  {
   Count=0;

   ten++;
   if(ten==10)
   {
    hundred++;
    ten=0;
   
    if(hundred==10)
    {
     thousand++;
     hundred=0;
    }
   }
  }
 }
   
 one=Sum-((thousand*1000)+(hundred*100)+(ten*10));
   
 Rpm[0]=thousand;
 Rpm[1]=hundred;
 Rpm[2]=ten;
 Rpm[3]=one;
 
 CString Data;
 Data.Format("%d%d%d%d",Rpm[0],Rpm[1],Rpm[2],Rpm[3]);

 m_TestEdit=Data;

 UpdateData(FALSE);

/*---------------------테스트 모드가 ON 모드만 테스트----------------*/

    CString csTmp1,csTmp2;
   
 csTmp1="#";
     if(ccModel.nMode1==TRUE)
 {
 csTmp1+="1";
 }
 if(ccModel.nMode2==TRUE)
 {
 csTmp1+="2";
 }
 if(ccModel.nMode3==TRUE)
 {
 csTmp1+="3";
 }

 int index = csTmp1.Find("#");//15
 int set[8];

 int Length =  csTmp1.GetLength();

 for(int i=0; i<Length; i++)
 {
 set[i]=atoi(csTmp1.Mid(index+i,1));  
 }

 for(int n=0; n<Length; n++)
 {
  TestMode(set[n]);
 }
 
// csTmp2.Format("%d",set[2]);
// AfxMessageBox(csTmp2);


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 이미지 -  ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/

//------MIL LIBRARY------------------------------------------------//
   MIL_ID MilSystem
   MIL_ID MilDisplay
  
   MIL_ID MilImage,                         /* Image buffer identifier.*/         
          MilOverlayImage;                  /* Overlay image.          */

 /* Restore the model image and display it */
   MbufRestore(SINGLE_MODEL_IMAGE, MilSystem, &MilImage);
   //------------------------------------------------------
  
  // 윈도우 창 디스플레이
  ///MdispSelect(MilDisplay, MilImage);
                         
   //Picture Box 상속 디스플레이
   Handle[0]= ((CWnd*)GetDlgItem(IDC_CAM1))->GetSafeHwnd();
   MdispSelectWindow(MilDisplay, MilImage, Handle[0]);
   //------------------------------------------------------

//------Gray    변경------------------------------------------------//
   float r, g, b, gray;

   r=m_pTestBitmap[ADD1]/255.0f;
   g=m_pTestBitmap[ADD2]/255.0f;
   b=m_pTestBitmap[ADD3]/255.0f;
   RGBToGrayMul(r,g,b,&gray);
   gray= (unsigned char)(gray*255.0);

   //++++++++++++++++++++++++++++
   if(gray > 100)//이미지 검출값
   //++++++++++++++++++++++++++++
   //++++++++++++++++++++++++++++

//----------------------------------------------------------------------------------------
//Image 수평 분할 display
/* CClientDC pDC(this);
 int Add_x,Add_y=0;
 int DivisionRate= PaletteSize_y*5;

 if(m_bPaletteChange)
 {
  for(y=0; y<PaletteSize_y+8; y++)
  {
   for(x=0; x<PaletteSize_x+8; x++)
   {
  // pDC.SetPixel(x+BMP_START_EDGE_X1-10,y+BMP_START_EDGE_Y1-10,RGB(122,123,102));
   pDC.SetPixel(x+BMP_START_EDGE_X1-4,y+BMP_START_EDGE_Y1-4,RGB(122,123,102));
   }
  }
  m_bPaletteChange=FALSE;
 }
 else
 {
  for(y=0; y<PaletteSize_y*ImageMaxNo; y++)
  {
  for(x=0; x<PaletteSize_x; x++)
  {
   if(y<DivisionRate)
   {
   pDC.SetPixel(x+BMP_START_EDGE_X1,y+BMP_START_EDGE_Y1,RGB(255,255,255));
   }
   else
   {  
   Add_x= PaletteSize_x*(y/DivisionRate)+(y/DivisionRate)*10;
   Add_y=DivisionRate*(y/DivisionRate);
   
   pDC.SetPixel((x+BMP_START_EDGE_X1)+Add_x,(y+BMP_START_EDGE_Y1)-Add_y,RGB(255,255,255));
   }
  } 
  }
 }

 //Image를 다섯개씩 분할 수평으로 디스플레이
 for(y=0; y<PaletteSize_y*ImageMaxNo; y++)
 {
  for(x=0; x<PaletteSize_x; x++)
  {
   if(y<DivisionRate)
   {
   pDC.SetPixel(x+BMP_START_EDGE_X1,y+BMP_START_EDGE_Y1,RGB(m_DisplayImg_A[(y*WidthLineSize)+(3*x)+2],m_DisplayImg_A[(y*WidthLineSize)+(3*x)+1],m_DisplayImg_A[(y*WidthLineSize)+(3*x)+0]));
   }
   else
   {  
   Add_x= PaletteSize_x*(y/DivisionRate)+(y/DivisionRate)*10;
   Add_y=DivisionRate*(y/DivisionRate);
   
   pDC.SetPixel((x+BMP_START_EDGE_X1)+Add_x,(y+BMP_START_EDGE_Y1)-Add_y,RGB(m_DisplayImg_A[(y*WidthLineSize)+(3*x)+2],m_DisplayImg_A[(y*WidthLineSize)+(3*x)+1],m_DisplayImg_A[(y*WidthLineSize)+(3*x)+0]));
   }
  } 
 }
//-------------------------------------------------------------------------------------------------
*/
/*
//-----------------------------------------------------------------------------------
//Binary File Save
//----------------------------------------------
// R  G  B    3Byte를 2Byte로 변환  
// 00000000  00000000
// 11111                R -5비트  32     256/8
//      111  111        G -6비트  64     256/4
//              11111   B -5비트  32     256/8
//----------------------------------------------
 //(128x(96*ImageNo))*2   한 픽셀 표현 2바이트 ,이미지 저장할 파일 사이즈
 int ImageFileSize=(PaletteSize_x*(PaletteSize_y*ImageMaxNo)*2);

 unsigned char *BinOutImg;
 BinOutImg = NULL;     //변경전 Image file size
 BinOutImg   = new unsigned char [3*WidthLineSize*(PaletteSize_y*ImageMaxNo)];

 index=0; n=0;

 for(y=0; y<PaletteSize_y*ImageMaxNo; y++)
 {
  for(x=0; x<PaletteSize_x; x++)
  {
   index=n*2;
   BinOutImg[index+0]=(((OutImg[(y*WidthLineSize)+(3*x)+2])/8)<<3)|(((OutImg[(y*WidthLineSize)+(3*x)+1])/4)>>3);
   BinOutImg[index+1]=(((OutImg[(y*WidthLineSize)+(3*x)+1])/4)<<5)|(((OutImg[(y*WidthLineSize)+(3*x)+0])/8));
   n++;
  }
 }
 FILE *outfile;
 CString csImageFile;

 csImageFile.Format("C:\\ModuleAging\\Bin\\%d.bin",PaletteSize_x);
 outfile = fopen(csImageFile,"wb");

 fwrite(BinOutImg,sizeof(char),ImageFileSize,outfile);
 fclose(outfile);

 if(BinOutImg) delete []BinOutImg;
//-----------------------------------------------------------------------------------
 //BMP File Save
 unsigned char *BmpOutImg=NULL;
 BmpOutImg = new unsigned char [(PaletteSize_y*ImageMaxNo)*(PaletteSize_x*24)*3];

 for(y=0; y<PaletteSize_y*ImageMaxNo; y++) //BMP 화일로 저장 하기위해 거꾸로 저장
 {
  y2=((PaletteSize_y*ImageMaxNo)-y);//-1 중요(최종 한줄 표현)
  for(x=0; x<PaletteSize_x; x++)
  {
   BmpOutImg[(y2*WidthLineSize)+(3*x)+2]=OutImg[(y*WidthLineSize)+(3*x)+2];
   BmpOutImg[(y2*WidthLineSize)+(3*x)+1]=OutImg[(y*WidthLineSize)+(3*x)+1];
   BmpOutImg[(y2*WidthLineSize)+(3*x)+0]=OutImg[(y*WidthLineSize)+(3*x)+0];
  }
 }

 DWORD dwBitsSize = sizeof(BITMAPINFOHEADER)+sizeof(RGBQUAD)*256+WidthLineSize*PaletteSize_y*sizeof(char);
 
 dibHi.biWidth=PaletteSize_x;
 dibHi.biHeight=PaletteSize_y*ImageMaxNo;
 dibHi.biBitCount =24;
 dibHi.biSizeImage = 3*WidthLineSize*(PaletteSize_y*ImageMaxNo);
 dibHi.biClrUsed = dibHi.biClrImportant =0;
 
 dibHf.bfType=0x4D42;
 dibHf.bfSize = dwBitsSize+sizeof(BITMAPFILEHEADER); // 전체파일 크기
 if(dibHi.biBitCount==24) dibHf.bfSize -= sizeof(RGBQUAD)*256; // no pallette
 dibHf.bfOffBits = dibHf.bfSize - WidthLineSize*PaletteSize_y*sizeof(char);
 dibHf.bfReserved1=dibHf.bfReserved2=0;

 FILE *outfile2;
 csImageFile.Format("C:\\ModuleAging\\EquipSys\\%d.bmp",PaletteSize_x);
 outfile2 = fopen(csImageFile,"wb");

 fwrite(&dibHf,sizeof(char),sizeof(BITMAPFILEHEADER),outfile2);
 fwrite(&dibHi,sizeof(char),sizeof(BITMAPINFOHEADER),outfile2);
 fwrite(BmpOutImg,sizeof(char),3*WidthLineSize*dibHi.biHeight,outfile2);
 fclose(outfile2);
 if(BmpOutImg) delete []BmpOutImg;
*/


/*--------------------------------------------------------------------------------------*/
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// - 그래픽 -  ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*--------------------------------------------------------------------------------------*/


CDC memDC;
CBitmap memBmp,*pOldBmp;
memDC.CreateCompatibleDC( &dc );
memBmp.CreateCompatibleBitmap( &dc,m_rectWindow.Width(),m_rectWindow.Height() );
pOldBmp = (CBitmap*)memDC.SelectObject( &memBmp );

if( memDC.GetSafeHdc() != NULL )

{   // memDC에 그린다..

    memDC.BitBlt( 0,0,m_rectWindow.Width(),m_rectWindow.Height(),&m_memBackDC, 0,0,SRCCOPY );   // 그리기
    memDC.BitBlt(
    dc.BitBlt( 0,0, nWidth, nHeight, &memDC, 0, 0, SRCCOPY );   // Main DC에 옮겨 쓰기
}

memDC.SelectObject( pOldBmp );

//######################
http://www.ucancode.net
//######################

//-------------------------------------------------------------------
BOOL Ellipse(int x1, int y1, int x2, int y2);

//-------------------------------------------------------------------
BOOL RoundRect(int x1, int y1, int x2, int y2, int x3, int y3);
BOOL RoundRect(PCRECT lpRect, POINT point);
When this member function executes, the rectangle is drawn from the (x1, y1) to the (x2, y2) points. The corners are rounded by an ellipse whose width would be x3 and the ellipse's height would be x3.
//-------------------------------------------------------------------
BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
BOOL Pie(LPCRECT lpRect, POINT ptStart, POINT ptEnd);
The (x1, y1) point determines the upper-left corner of the rectangle in which the ellipse that represents the pie fits. The (x2, y2) point is the bottom-right corner of the rectangle. These two points can also be combined in a RECT or a CRect variable and passed as the lpRect value.

The (x3, y3) point, that can also supplied as a POINT or CPoint for lpStart argument, specifies the starting corner of the pie in a default counterclockwise direction.

The (x4, y4) point, or ptEnd argument, species the end point of the pie.

To complete the pie, a line is drawn from (x3, y3) to the center and from the center to the (x4, y4) points.
//-------------------------------------------------------------------

To draw an arc, you can use the CDC::Arc() method whose syntax is:

BOOL Arc(int x1, int y1, int x2, int y2,
 int x3, int y3, int x4, int y4);
Besides the left (x1, y1) and the right (x2, y2) borders of the rectangle in which the arc would fit, an arc must specify where it starts and where it ends. These additional points are set as the (x3, y3) and (x4, y4) points of the figure. Based on this, the above arc can be illustrated as follows:
//-------------------------------------------------------------------
This method uses the same arguments as Arc(). The difference is that while Arc() starts drawing at (x3, y3), ArcTo() does not inherently control the drawing starting point. It refers to the current point, exactly like the LineTo() (and the PolylineTo()) method. Therefore, if you want to specify where the drawing should start, can call CDC::MoveTo() before ArcTo(). Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
 CRect Recto(20, 20, 226, 144);
 CPoint Pt1(202, 115);
 CPoint Pt2(105, 32);

 pDC->MoveTo(207, 155);
 pDC->ArcTo(Recto, Pt1, Pt2);
}
 
//------------------------------------------------------------------------
You may wonder why the arc is drawn to the right side of a vertical line that would cross the center of the ellipse instead of the left. This is because the drawing of an arc is performed from right to left or from bottom to up, in the opposite direction of the clock. This is known as the counterclockwise direction. To control this orientation, the CDC class is equipped with the SetArcDirection() method. Its syntax is:

int SetArcDirection(int nArcDirection);
This method specifies the direction the Arc() method should follow from the starting to the end points. The argument passed as nArcDirection controls this orientation. It can have the following values:

  Value Orientation
  AD_CLOCKWISE The figure is drawn clockwise
  AD_COUNTERCLOCKWISE The figure is drawn counterclockwise

The default value of the direction is AD_COUNTERCLOCKWISE. Therefore, this would be used if you do not specify a direction. Here is an example that uses the same values as above with a different orientation:

void CExoView::OnDraw(CDC* pDC)
{
 pDC->SetArcDirection(AD_CLOCKWISE);

 pDC->Arc(20, 20, 226, 144, 202, 115, 105, 32);
}
//------------------------------------------------------------------------
You can (also) draw an arc using the CDC::AngleArc() method. Its syntax is:

BOOL AngleArc(int x, int y, int nRadius, float fStartAngle, float fSweepAngle);
This member function draws a line and an arc connected. The arc is based on a circle and not an ellipse. This implies that the arc fits inside a square and not a rectangle. The circle that would be the base of the arc is defined by its center located at C(x, y) with a radius of nRadius. The arc starts at an angle of fStartAngle. The angle is based on the x axis and must be positive. That is, it must range from 0° to 360°. If you want to specify an angle that is below the x axis, such as -15°, use 360º-15°=345°. The last argument, fSweepAngle, is the angular area covered by the arc.

The AngleArc() method does not control where it starts drawing. This means that it starts at the origin, unless a previous call to MoveTo() specified the beginning of the drawing.

Here is an example:

void CExoView::OnDraw(CDC* pDC)
{
 pDC->MoveTo(52, 28);
 pDC->AngleArc(120, 45, 142, 345, -65);
}


//------십자선 그리기------------------------------------------------//
 CClientDC pDC(this);
 int CenterX=349;int CenterY=298;
 int LineSizeX=0; int LineSizeY=0;

 LineSizeX=340;
 LineSizeY=260;

 CPen penRectBlack(PS_SOLID,1,RGB(0,0,255));
 CPen *pOldPen;
 
 pDC.SelectObject(&penRectBlack);
 pOldPen = pDC.SelectObject(&penRectBlack);

 pDC.MoveTo(CenterX,CenterY-LineSizeY);
 pDC.LineTo(CenterX,CenterY+LineSizeY);

 pDC.MoveTo(CenterX-LineSizeX,CenterY);
 pDC.LineTo(CenterX+LineSizeX,CenterY);

 pDC.SelectObject(pOldPen);
 penRectBlack.DeleteObject();
}

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

//------삼각형 그리기------------------------------------------------//
 //CDraw1Doc* pDoc = GetDocument();
 //ASSERT_VALID(pDoc);

 CBrush NewBrush(RGB(255, 2, 5));
 CBrush *pBrush;
 
 CPoint Pt[3];

 CDC *pDC = GetDC();

 // Top Triangle
 Pt[0] = CPoint(125,  10);
 Pt[1] = CPoint( 95,  70);
 Pt[2] = CPoint(155,  70);

 pBrush = pDC->SelectObject(&NewBrush);
 pDC->Polygon(Pt, 3);

 // Left Triangle
 Pt[0] = CPoint( 80,  80);
 Pt[1] = CPoint( 20, 110);
 Pt[2] = CPoint( 80, 140);

 pDC->Polygon(Pt, 3);

 // Bottom Triangle
 Pt[0] = CPoint( 95, 155);
 Pt[1] = CPoint(125, 215);
 Pt[2] = CPoint(155, 155);
 
 pDC->Polygon(Pt, 3);

 // Right Triangle
 Pt[0] = CPoint(170,  80);
 Pt[1] = CPoint(170, 140);
 Pt[2] = CPoint(230, 110);

 pDC->Polygon(Pt, 3);

 pDC->SelectObject(pBrush);

//------사각그리기------------------------------------------------//
 CPen penRectBlack(PS_SOLID,1,RGB(255,0,0));
 pDC->SelectObject(&penRectBlack);
 pDC->MoveTo(m_MatchPos.left,m_MatchPos.top);
 pDC->LineTo(m_MatchPos.right,m_MatchPos.top);
 pDC->LineTo(m_MatchPos.right,m_MatchPos.bottom);
 pDC->LineTo(m_MatchPos.left,m_MatchPos.bottom);
 pDC->LineTo(m_MatchPos.left,m_MatchPos.top);


//------Text 출력------------------------------------------------//
 CFont *Font,*oldFont;
 Font=new CFont;

 LOGFONT logFont; int nFontHight=25;
 logFont.lfStrikeOut=FALSE;//가운데 선긋기
 logFont.lfItalic=TRUE;logFont.lfUnderline=FALSE;
 logFont.lfEscapement= 0;logFont.lfHeight=nFontHight;
 logFont.lfCharSet=HANGEUL_CHARSET;//ANSI_CHARSET;

// Font->CreatePointFont(240,_T("굴림"));
// Font->GetLogFont(&logFont);
 Font->CreateFontIndirect(&logFont);
 oldFont=dc.SelectObject(Font);

 dc.SetBkMode(TRANSPARENT);//dc.SetTextCharacterExtra(2);//행간격
 dc.SetTextColor(RGB(255,0,0));//dc.SetBkColor(RGB(255,0,0));
 //---------------------------------------------
 nTextLine_x=SpotRect.left;//+((SpotRect.right-SpotRect.left)/2);
 nTextLine_y=AddBottom+MAINDIS_START_Y-58-8;
 dc.TextOut(nTextLine_x,nTextLine_y-15,csLineSize_x);//x,가로 치수 텍스트

 dc.SelectObject(oldFont);delete Font;

 Font=new CFont;
 logFont.lfEscapement= -900;logFont.lfHeight=nFontHight;
 Font->CreateFontIndirect(&logFont);
 oldFont=dc.SelectObject(Font);

 nTextLine_x=SpotRect.right+16;nTextLine_y=AddBottom+MAINDIS_START_Y-25;
 dc.TextOut(nTextLine_x,nTextLine_y-15,csLineSize_y);//y,세로 치수 텍스트
// CRect rect;
// rect.left=nTextLine_x; rect.right=nTextLine_x+30;
// rect.top=nTextLine_y-15;rect.bottom=nTextLine_y+30;
/// dc.DrawText(csLineSize_y,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);//y,세로 치수 텍스트
 //---------------------------------------------

 dc.SelectObject(oldFont);delete Font;
 //dc.SelectObject(oldFont);Font.DeleteObject();
 dc.SelectObject(pOldPen);NewPen.DeleteObject();

/*-------------------------------------------------------------------
 CFont Font,*oldFont;
 LOGFONT logFont;

 int m_nFontSize=14;
 CString m_strFont="바탕체";
 Font.CreateFont(m_nFontSize,m_nFontSize,-900,0,FW_DONTCARE,FALSE,
      FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,
      CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH,
      m_strFont);

 oldFont=dc.SelectObject(&Font);
 dc.SetBkMode(TRANSPARENT);//dc.SetTextCharacterExtra(2);//행간격
 dc.SetTextColor(RGB(255,0,0));//dc.SetBkColor(RGB(255,0,0));
 //---------------------------------------------
 nTextLine_x=SpotRect.left;//+((SpotRect.right-SpotRect.left)/2);
 nTextLine_y=AddBottom+MAINDIS_START_Y-60;
 dc.TextOut(nTextLine_x,nTextLine_y-15,csLineSize_x);//x,가로 치수 텍스트
 dc.SelectObject(oldFont);Font.DeleteObject();

 nTextLine_x=SpotRect.right+6;nTextLine_y=AddBottom+MAINDIS_START_Y-20;
// dc.TextOut(nTextLine_x,nTextLine_y-15,csLineSize_y);//y,세로 치수 텍스트
 CRect rect;
 rect.left=nTextLine_x; rect.right=nTextLine_x+30;
 rect.top=nTextLine_y-15;rect.bottom=nTextLine_y+30;

 dc.DrawText(csLineSize_y,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);//y,세로 치수 텍스트
 //---------------------------------------------

 dc.SelectObject(oldFont);Font.DeleteObject();
 dc.SelectObject(pOldPen);NewPen.DeleteObject();


/*--------------------사인파그래프---------------------------*/

 for (f=-500;f<2000;f++) {
 y=(int)(sin(f*3.14/180)*100);
 SetPixel(hdc, (int)f, y,RGB(0,0,0));
 }
/*--------------------그래프--------------------------------*/
void CGrapeDlg::OnPaint()
{
 CPaintDC dc(this); // device context for painting
 
 // TODO: Add your message handler code here
  for(int i=0; i<3; i++)
 {
  GrapeDrawEX(i);
 }
 // Do not call CDialog::OnPaint() for painting messages
}

void CGrapeDlg::GrapeDrawEX(int SetNo)
{
 CClientDC dc(this);

 int xStartPoint;
 int yStartPoint;
 COLORREF GrapeLineColor;

 if(SetNo==0)
 {
  xStartPoint=32;
  yStartPoint=150;
  GrapeLineColor= RGB(0,250,250);
 }
 else if(SetNo==1)
 {
 xStartPoint=32;
 yStartPoint=350;
 GrapeLineColor= RGB(0,250,0);
 }
 else if(SetNo==2)
 {
 xStartPoint=32;
 yStartPoint=550;
 GrapeLineColor= RGB(0,0,250);
 }
 int xExpand=22;/*x시간확장 11 or 22*/
 int yExpand=(40/2)+(40/2);/*y온도 범위확장 20 or 40*/
 int xLimit=40;/*y_pixel 나누기 단위 20 or 40*/
 int yLimit=40/2; /*x_pixel 나누기 단위* 20 or 40*/
 int yTatalNo=200/2; /*100 or 200 select*/

 int xwidth=960;/*480 or 960*/
 int yhigh=200/2;/*100 or 200*/
 int width=xwidth+xStartPoint+xExpand; //width,high
 int high=yhigh+yStartPoint+yExpand;

 int ThermoBufX[24];
 int ThermoBuf[24];
 ThermoBuf[0]=20;
 ThermoBuf[1]=30;
 ThermoBuf[2]=40;
 ThermoBuf[3]=45;
 ThermoBuf[4]=50;
 ThermoBuf[5]=40;
 ThermoBuf[6]=40;
 ThermoBuf[7]=50;
 ThermoBuf[8]=50;
 ThermoBuf[9]=55;
 ThermoBuf[10]=60;
 ThermoBuf[11]=70;
 ThermoBuf[12]=80;
 ThermoBuf[13]=90;
 ThermoBuf[14]=100;
 ThermoBuf[15]=105;
 ThermoBuf[16]=104;
 ThermoBuf[17]=100;
 ThermoBuf[18]=97;
 ThermoBuf[19]=98;
 ThermoBuf[20]=100;
 ThermoBuf[21]=101;
 ThermoBuf[22]=100;
 ThermoBuf[23]=100;
/*---------------Backgndbrush---------*/
 COLORREF m_BackgndBrush= RGB(0,0,0);
 CBrush brush(m_BackgndBrush),*pOldBrush;
 pOldBrush = (CBrush *)dc.SelectObject(&brush);
 dc.Rectangle(xStartPoint,yStartPoint,width,high);
/*---------------BaseTime/Thermo_brush---------*/
 COLORREF m_BaseTimebrush= RGB(250,250,250);
 CBrush brush2(m_BaseTimebrush);
 dc.SelectObject(&brush2);
 dc.Rectangle(xStartPoint-27,high,width+2,high+20);/*time*/
 dc.Rectangle(xStartPoint-27,yStartPoint,xStartPoint,high+20);/*thermo*/

/*---------------단위pixel-------------*/
 for(int i=xStartPoint; i<width; i+=xLimit)
 {
  for(int n=yStartPoint; n<high; n+=yLimit)
  {
  dc.SetPixel(i,n,RGB(0,250,250));
  }
 }
/*----------------전체 테두리-중간 Rect1-----------------*/
 CPen penRectBlue1(PS_SOLID,2,RGB(50,0,250)),*pOldPen;
 pOldPen = dc.SelectObject(&penRectBlue1);
 dc.MoveTo(xStartPoint-27,yStartPoint);
 dc.LineTo(width,yStartPoint);
 dc.LineTo(width,high+20);
 dc.LineTo(xStartPoint-27,high+20);
 dc.LineTo(xStartPoint-27,yStartPoint);
/*---------------전체 테두리-안쪽-------------------*/
 CPen penRectYello2(PS_SOLID,2,RGB(250,250,0));
 dc.SelectObject(&penRectYello2);
 dc.MoveTo(xStartPoint+4,yStartPoint+4);
 dc.LineTo(width-4,yStartPoint+4);
 dc.LineTo(width-4,high-4);
 dc.LineTo(xStartPoint+4,high-4);
 dc.LineTo(xStartPoint+4,yStartPoint+4);

/*---------------전체 테두리-바깥  Rect3-------------------*/
 CPen penRectBlack(PS_SOLID,4,RGB(0,250,250));
 dc.SelectObject(&penRectBlack);
 dc.MoveTo(xStartPoint-3-27,yStartPoint-3);
 dc.LineTo(width+3,yStartPoint-3);
 dc.LineTo(width+3,high+20+3);
 dc.LineTo(xStartPoint-3-27,high+20+3);
 dc.LineTo(xStartPoint-3-27,yStartPoint-3);
/*---------------온도 기준 line-------------------*/
 CPen penRectBlack2(PS_SOLID,2,RGB(0,0,0));
 dc.SelectObject(&penRectBlack2);
 dc.MoveTo(xStartPoint-26,high);
 dc.LineTo(xStartPoint,high);
/*---------------각시간 지시선 ----------------------*/
 CPen penWhite(PS_SOLID,2,RGB(250,250,250));
 dc.SelectObject(&penWhite);

 for(int n2=xStartPoint+xLimit; n2<width; n2+=xLimit)
 {
 dc.MoveTo(n2,high-6);
 dc.LineTo(n2,high-16);
 }
/*---------------각온도 지시선-----------------------*/
 for(int n3=yStartPoint+yLimit; n3<high; n3+=yLimit)
 {
 dc.MoveTo(xStartPoint+6,n3);
 dc.LineTo(xStartPoint+16,n3);
 }
/*--------------x_BaseTime출력Text---------------*/
 CString TimeText;
 int time=0;
// ModifyStyleEx(0,WS_BORDER,SWP_DRAWFRAME);
 dc.SetBkMode(TRANSPARENT);
 dc.SetTextColor(RGB(50,0,0));
 for(int a2=xStartPoint+xLimit; a2<width; a2+=xLimit)
 {
  time++;
  TimeText.Format("%d",time);
  dc.TextOut(a2-6,high+3,TimeText);
 }
 dc.SetTextColor(RGB(250,0,0));
 dc.TextOut(xStartPoint-25,yStartPoint-24,"( 'C )");
 dc.SetTextColor(RGB(0,0,250));
 dc.TextOut(xStartPoint+36,high+26,"TIME- - -");
/*----------------y_Base온도Text--------------------*/
 CString ThermoText;
 for(int a3=yStartPoint+yLimit; a3<high; a3+=yLimit)
 {
  if(yhigh==100)
  {
  ThermoText.Format("%d",yTatalNo-((a3-yLimit)-yStartPoint)+yLimit);
  dc.TextOut(xStartPoint-24,a3-8,ThermoText);
  }
  else if(yhigh==200)
  {
  ThermoText.Format("%d",(yTatalNo-((a3-yLimit)-yStartPoint)+yLimit)/2);
  dc.TextOut(xStartPoint-24,a3-8,ThermoText);
  }
 }
/*------------온도 point 꼭지점 ----------*/  
 int count1=0;
 int xMove=3;
 int point_x=6;
 int point_y=6;
 CPen penWhite2(PS_SOLID,4,RGB(250,0,50));
 dc.SelectObject(&penWhite2);

 for(int c=xStartPoint+xLimit; c<width; c+=xLimit)
 {
  ThermoBufX[count1]=c;
  count1++;
 }
 for(int c2=0; c2<24; c2++)
 {
  if(yTatalNo==100)
  {
  dc.Ellipse(ThermoBufX[c2]-xMove,(yTatalNo-ThermoBuf[c2])+yStartPoint+yExpand,ThermoBufX[c2]+point_x-xMove,(yTatalNo-ThermoBuf[c2])+yStartPoint+yExpand+point_y);
  }
  else if(yTatalNo==200)
  {
  dc.Ellipse(ThermoBufX[c2]-xMove,((yTatalNo/2)-ThermoBuf[c2])*2+yStartPoint+yExpand,ThermoBufX[c2]+point_x-xMove,((yTatalNo/2)-ThermoBuf[c2])*2+yStartPoint+yExpand+point_y);
  }
 }
/*-------------온도 그래프 실선--------*/
int count2=0;
int GrapeStartPoint=yhigh+yStartPoint+yExpand-4;
 CPen penGrapeRed(PS_SOLID,1,GrapeLineColor);
 dc.SelectObject(&penGrapeRed);
 dc.MoveTo(xStartPoint+4,GrapeStartPoint);

 for(int d=xStartPoint+xLimit; d<width; d+=xLimit)
 {
  ThermoBufX[count2]=d;
  count2++;
 }
 for(int d2=0; d2<24; d2++)
  {
   if(yTatalNo==100)
   {
   dc.LineTo(ThermoBufX[d2],(yTatalNo-ThermoBuf[d2])+yStartPoint+yExpand+3);
   }
   else if(yTatalNo==200)
   {
   dc.LineTo(ThermoBufX[d2],((yTatalNo/2)-ThermoBuf[d2])*2+yStartPoint+yExpand+3);
   }
  }
/*--------------온도출력 Text---------------*/
// ModifyStyleEx(WS_BORDER,0,SWP_DRAWFRAME);
 CString TextData;
 dc.SetBkMode(TRANSPARENT);
 dc.SetTextColor(RGB(250,250,250));

 for(int a=0; a<24; a++)
 {
  TextData.Format("%d",ThermoBuf[a]);
  if(yTatalNo==100)
  {
  dc.TextOut(ThermoBufX[a]-6,(yTatalNo-ThermoBuf[a])+yStartPoint+yExpand-20,TextData);
  }
  else if(yTatalNo==200)
  {
  dc.TextOut(ThermoBufX[a]-6,((yTatalNo/2)-ThermoBuf[a])*2+yStartPoint+yExpand-20,TextData);
  }
 }
/*-----------------------------------------------*/
 dc.SelectObject(pOldBrush);
 dc.SelectObject(pOldPen);
/*------------------------------------------------*/
Tag |

Fedora10 에서 VirtualBox 설치하기!

from Info/Tools 2009/02/21 13:29 view 489143
링크 : http://www.derekhildreth.com/blog/how-to-install-virtualbox-on-fedora-10-tutorial/

This is a tutorial on how to get VirtualBox up and running on Fedora 10. Also, this tutorial is for the 32-Bit version of VirtualBox, so you’ll have to customize a little more to get the 64-bit version running. Everything in the “code” sections should be copy/pasted/typed into the terminal. Right, let’s get to it:

PreStep.) Open the terminal and get into super user mode:
Code:
su -
1.) Get the latest VirtualBox package (as of now, 2.0.6) from the VirtualBox website for Fedora 9 and install it (generally, after a few months, the Fedora 10 link will be available).
Code:

wget http://download.virtualbox.org/virtualbox/2.0.6/VirtualBox-2.0.6_39765_fedora9-1.i386.rpm && rpm -ivh VirtualBox-2.0.6_39765_fedora9-1.i386.rpm

2.) Get the kernel-devel package:
Code:
yum install make automake autoconf gcc kernel-devel dkms
3.) Run the setup file for VirtualBox:
Code:
/etc/init.d/vboxdrv setup
4.) Add yourself to the “vboxusers” group and fix SELinux Permissions:
Code:
usermod -G vboxusers -a username
chcon -t textrel_shlib_t /usr/lib/virtualbox/VirtualBox.so
5.) Run, and enjoy!
Code:
VirtualBox
failed to create the virtualbox com object
Callee RC:
        NS_ERROR_FACTORY_NOT_REGISTERED (0×80040154)
에러가 발생한다면
/tmp/.vbox-your_login-ipc 의 root - root 를 your_login-your_login 로 바꿔주자.
또는 /tmp/.vobx-your_login-ipc 파일을 remove 하면 알아서 다시 생성 해줌으로 알아서..-_ㅡ;;



6.) To Get USB Support:

1 - create a new group called “usb”;
2 - locate file usbfs: in my case is /sys/bus/usb/drivers (I suggest to find the file with a usb device inserted;
3 - modify file /etc/fstab inserting a line containing the right path and the number corresponding the “usb” group :
none /sys/bus/usb/drivers usbfs devgid=503,devmode=664 0 0
4 - command mount -a;
5 - start VB and try…;

Source: Fedora Forums
7.) To Properly Backup the VirtualBox Machine (.vdi):

Please refer to my other page here:

How To: Properly Backup a VirtualBox Machine (.VDI)

8.) To Get Sound Working:

Highlight your virtual machine and click on the “Settings” button. Click on the “Sound” category, and then check the “Enable Sound” option. In the drop-down box, select “PulseAudio”. You should now have sound.
VNC Client for GNOME ( vinagre )

리눅스간에 사용할만한 원격제어 툴..
크기조정, 전체화면 같은 기본적인 기능을 잘 지원한다.
클립보드와 같은 기능도 지원하니 매우 좋음.. ㅋㅋ;;

1. 원격 제어를 허용한다. 아무나 접속하는 것을 막기위해 비밀번호를 설정하고 접속확인은 체크 하면 원격지에서 허용해줘야 가능하므로 -_ㅡ 패스~
사용자 삽입 이미지

2. 로그아웃 했을 때 로그오프를 수행하도록 해서 원격지 컴퓨터를 보호한다.
사용자 삽입 이미지

3. vinagre 를 설치해다면 아이피를 쳐서 접속을 해본다.
사용자 삽입 이미지

4. 원격지 컴퓨터에서 방화벽 포트를 개방해줘야 접속이 가능해진다.
사용자 삽입 이미지

Fedora 배포 사이트외 패키지를 받자.

from Info/OS 2009/02/20 10:31 view 33111

코덱이랑 등등 찾을 수 없어 헤매던중 찾은 정보.


/* 09.2.20 조금 버그가 있는 거 같다 -_ㅡ 페도라가 패닉이 되는 상태 발생.... */


다음 사이트에 접속하여 파일을 다운로드 받습니다. 버전에 맞는 걸 골라서~!

http://ftp.freshrpms.net/pub/freshrpms/fedora/

다운로드 받은 파일을 rpm -Uivh freshrpmsxxx.rpm명령으로 설치하시고

아래 명령들을 수행하세요.

일반적으로 페도라 배포 사이트에는 없는 패키지들을 설치.

Tag | ,
  1.   프로그래밍 언어란?

    • 사전적의미 : 컴퓨터의 프로그램을 작성하기 위해 고안된 언어.
    • 우리가 알고 있는 기계어조차도 CPU가 대응시켜준 의미를 따라 움직이는 것이다.
    • 프로그래밍 언어를 통해 의미가 부여된 텍스트 데이터는 소스코드가 되고 다시 프로그램이 된다.
  2. 구조적 프로그래밍 언어

    • 다익스트라가 만든 것으로 프로그램의 논리 구조를 단순화시켜 이해하기 쉬운 작은 서브 프로그램들을 사용해 전체 프로그램을 구성하는 개념.

      • 작은 서브 프로그램들을 이해하면 전체 프로그램을 이해하기가 수월해진다.
  3. 프로그래밍 언어의 분류

    • 어떤 패러다임을 통해 프로그래밍 할 것인지를 결정한 후 그 패러다임에 맞는 프로그래밍 언어를 선택하기 위해서 분류를 한다.
  4. 프로그래밍 언어의 해석

    • 프로그래머가 적어놓은 내용을 해석해 기계에게 직접 명령을 내릴 수 있는 형태로 바꿔주는 컴파일러가 존재한다.
    • 컴파일러는 기계와 프로그래머의 의사소통을 도와주는 통역사와 같은 일을 한다.
    • 오토마타를 사용하여 함수의 파라미터에 함수가 사용될 수 있고, 수 혹은 변수의 대체로 함수의 반환값이 사용될 수도 있는 상황을 '단순화' 한다.
  5. 프로그래밍 언어 VS 일반 언어

    • 프로그래밍 언어는 컴파일러가 그 언어를 이해해야 한다. 컴파일러가 해석할 수 있을 때 코드가 유효해지는 것이다.
    • 사람은 언어를 이해할 때 기계처럼 정해진 대로만 이해하지 않는다. 구문 요소 중 몇 가지를 빼거나 순서를 바꿔도 이해 할 수 있다.
  6. Why is C?

    • 대부분의 언어들이 C 언어를 기반으로 변형 됐으며, 아직까지도 C는 여러 분야에서 많이 사용되고 있다.
    • 표현의 단순함과 기계어와 가까운 형태를 취하고 있다. 인라인 어셈블리를 지원하고 있다.
    • 네이티브 : C언어처럼 기계어로 바로 변환하는 형태로 포인터에 대한 문제를 해결해야 한다.
    • 인터프리터 : 코드의 실행을 인터프리터에서 처리하며 플랫폼을 고려하지 않아도 이기종간의 호환성이 보장된다. 하지만 그만큼 기계에서 멀리 떨어져 있기 때문에 여러가지 근본적인 것들을 이해할 수 없다는 문제를 야기하기도 한다.
  7. C언어는 사라질것인가?

    • C언어는 이미 기계 그 자체가 돼 버렸기 때문에 없어지지 않을 것이다.
    • C는 기계어에 가장 가까운 고급언어로 현재 가장 많이 사용되고 있다.
    • 상당한 플랫폼들에서 C언어를 사용하고 있기 때문에 CPU의 구조가 바뀌면 흔들릴 수도 있지만.....과연?

참고문서 : <마소2009.2월호 special report 2>C언어로 보는 구조적 프로그래밍 언어의 이해-권용휘

이 글은 스프링노트에서 작성되었습니다.

커널 동기화 방법

from Study/System 2009/02/16 14:08 view 31632
  1. 원자적 동작(Atomic Operation)

    • 중단됨이 없이 한번에 실행되는 명령. 원자(Atom)가 더 이상 쪼갤 수 없는 원소를 의미하듯 원자적 동작은 나눠지지 않는 명령등을 의미한다.
  2. 원자적 정수연산, 원자적 비트연산

    • 원자적 정수연산은 특별한 자료구조인 atomic_t를 사용한다.

      1. 원자적인 함수들이 다른 자료형에 잘못 사용되는 것을 방지.
      2. 원자적동작이 엘리어스(alias)가 아닌 실제 메모리 주소를 사용하게 한다.
      3. 컴파일러가 이 자료형으로의 접근을 잘못 최적화하지 않도록 방지.
      4. 아키텍처에 따라 다른 구현을 감춰주는 역할.
    • 커널코드 작성시 모든 아키텍처에서 사용가능한 함수를 확인해 보아야 한다.
  3. 스핀락(Spin Lock)

    • 최대한 하나의 스레드에 의해 잠길 수 있는 락을 말한다.

      1. 만약 어떤 스레드가 이미 잠겨진 스핀락을 다시 잠그려 시도한다면 그 스레드는 루프(Busy Loop)를 돌면서(Spin)락을 잠글 수 있을때 까지 기다린다.
      2. 이러한 스피닝(Spinning)은 동시에 하나 이상의 스레드가 같은 위험구역에 진입하는 것을 방지해 준다.
    • 다른 스레드들을 스핀하도록(프로세스 시간을 소모함) 하므로 두번의 컨텍스트 스위칭 시간보다 짥게 잡고 있도록 하는 것(휴면방식을 사용하는것) 이 중요하다.
    • 프로세서가 하나인 시스템 에서도 인터럽트 핸들러가 공유 데이터를 접근하는 것을 방지하기 위해 인터럽트를 비활성화해야 한다.
    • 실제로 보호가 필요한 것은 코드 자체가 아닌 위험구역 안에 있는 데이터이므로 락을 특정한 데이터와 관련시키는 것이 좋다. "struct foo 는 foo_lock 으로 잠김"
  4. 스핀락과 보톰하프(Bottom Half)

    • 보톰하프는 프로세스 컨텍스트 코드를 선점할 수 있으므로, 만약 어떤 데이터가 보톰하프와 프로세스 컨텍스트간에 공유된다면 락을 사용함과 함께 보톰하프를 비활성화시켜 데이터를 보호해야 한다.

      • 프로세스 컨텍스트란 ? 프로세서 고유 컨텍스트(Processor Specific Context) 프로세스는 시스템의 현재 상태의 총합 으로 생각할 수 있다. 프로세스는 실행될 때마다, 프로세서의 레지스터와 스택 등을 사용 한다. 이것이 프로세스 컨텍스트이며, 프로세스가 중단될 때 CPU 고유의 컨텍스트들은 모두 그 프로세스의 task_struct에 저장되어야 한다. 스케쥴러가 이 프로세스를 다시 시작할 때, 이 컨텍스트는 이 정보로부터 복구된다.
  5.  Reader 와 Writer 스핀락

    • 리스트가 갱신(쓰기)되는 경우에는 다른 코드가 동시에 리스트에 쓰거나 읽지 않도록 해야 한다. 상호배제(Mutual Exclusion)가 필요하다.
    • 리스트를 탐색(읽기)하는 경우에는 다른 코드가 동시에 리스트에 쓰는 것만을 방지하면 된다. 쓰기작업이 없다면 동시에 여러 곳에 탐색이 가능하다.
    • 자료구조의 사용이 Reader/Writer로 확연히 구분되는 경우(생산자/소비자)에는 락킹 메커니즘은 Reader/Wrtier 스핀락을 제공한다.
    1. rwlock_t   mr_rwlock = RW_LOCK_UNLOCKED;
    2. read_lock(&mr_rwlock);
    3. /* 위험 구역(읽기 전용) */
    4. read_unlock(&mr_rwlock);
    5. write_lock(&mr_rwlock);

    6. /* 위험 구역(읽기, 쓰기 가능) */
    7. write_unlock(&mr_rwlock);
    • 대기중인 writer는 모든 Reader가 락을 해제할 때까지 락을 잠그지 못하게 되므로 리더가 상당 수 있는 경우 기아상태가 발생하게 될 수 있다.
  6. 세마포어

    • 락을 잡고 있는 시간이 길어지거나 락을 잡은 채 휴면해야 하는 경우에 사용한다.
    • 동작시나리오

      1. 어떤 태스크가 이미 잠겨진 세마포어를 잠그려 하는 경우, 세마포어는 그 태스크를 대기큐로 삽입하고 해당 태스크를 휴면 상태로 만든다.
      2. 프로세서는 다른 코드를 실행할 수 있게 된다.
      3. 세마포어를 잡고 있는 프로세스가 락을 해제하면, 대기큐에 있는 하나의 태스크가 깨어나서 세마포어를 잡게 된다.
    • 바쁜 루프로 시간을 소모하지 않기 때문에 스핀락보다 더 나은 활용도를 보여주지만 스핀락에 비해 세마포어는 훨씬 많은 부가작업이 필요하다.( 인생은 Trade-Off -_ㅡ;; )
    • 세마포어의 휴면 동작이 주는 의미

      1. 락을 기다리는 태스크들이 휴면하게 되므로 세마포어는 락을 오랫동안 잡게 되는 상황에 적합하다.
      2. 락을 잡고 있는 시간이 짧을 경우 휴면하고 대기큐를 관리하고 다시 깨워주는 추가작업들이 락을 잡고 있는 시간보다 길어질 가능성이 있다.(비효율적.)
      3. 스레드의 실행은 락 경쟁에서 휴면 상태가 될 수 있고 인터럽트 컨텍스트는 스케줄이 불가능하기 때문에 세마포어는 오직 프로세스 컨텍스트에서만 얻을 수 있다.
      4. 세마포어를 잡은채로 휴면할 경우 다른 프로세스가 같은 세마포어를 잡으려 하더라도 데드락에 빠지지 않는다.( 두번째 스레드 역시 휴면되므로 결국 첫번째 스레드가 실행)
      5. 세마포어를 사용할 경우 스핀락을 잡고 있어서는 안되는데, 왜냐하면 세마포어를 잡으려면 휴면해야 하는데 스핀락을 잡고 있는 상태에서는 휴면해서는 안된다.
    • 세마포어 VS 스핀락

      1. 락을 잡고 있는 시간을 근거로 결정을 내려야 한다.
      2. 세마포어는 커널 선점을 비활성화하지 않으므로 세마포어를 잡고 있는 코드는 선점될 수 있다.( 스케줄링에 불리하게 작용하지 않는다. )


         요구사항  추천
         락 부담이 적어야 하는 경우 스핀락
         락 기간이 짧은 경우 스핀락
         락 기간이 긴 경우 세마포어
         인터럽트 핸들러에서 락을 해야 하는 경우 반드시 스핀락(스케줄링)
         락을 소유한 채 휴면해야 하는 경우 반드시 세마포어
    • 세마포어는 동시에 여러 스레드가 같은 락을 잠글 수 있다. 선언시 그 숫자를 지정할 수 있다.

      1. 락의 갯수를 1로 지정하여 하나의 스레드만이 이 락을 잡을 수 있도록 한것을 바이너리 세마포어, 상호배제 관점에서의 뮤텍스라고 부른다.
      2. 카운팅 세마포어는 다수의 스레드가 동시에 같은 위험구역에 진입할 수 있도록 하므로 상호배제를 보장하지 않는다.
    • Reader-Writer 세마포어

      1. 모든 Reader-Writer 세마포어는 뮤텍스이다.
      2. Wirter 가 없는 한 다수의 Reader가 락을 소유할 수 있고 Reader 가 없는 상황에서 오직 하나의 Writer 만 락을 소유할 수 있다.
  7. 완료 변수( Completion Variable )

    • 커널의 두 태스크를 동기화시키기 위해 사용, 한 태스크가 이 변수를 통해 다른 태스크로 이벤트를 알려주는 식으로 동작한다.
    • 세마포어를 대신하여 간단히 사용하기 위해 제공되는 방법이다.
    • complete() 을 호출하여 완료변수에 시그널 되기를 기다리는 대기중인 태스크들을 깨어나도록 하는 방법.
  8. 큰 커널 락(BKL, Big Kernel Lock)

    • 특성

      1. 소유한 상태에서 휴면할 수 있다.
      2. BKL이 잠겨있는 경우 커널 선점은 비활성화 된다.
      3. 재귀적인 락이다.
      4. 오직 프로세스 컨텍스트에서만 사용가능하다.
      5. 이것은 필요악이다. 악마의 현신!!
    1. lock_kernel();
    2. /*
    3.  다른 모든 BKL 사용자들과 동기화되는 위험 지역..
    4.  여기서는 안전하게 휴면할 수 있으며, 휴면할 경우 락이 자동적으로 해제된다. 또 휴면했다가 다시 스케줄링되면 자동적으로 락을 얻는다.
    5. 즉, 어느 경우이든 데드락은 피할 수 있지만, 정말로 여기서 데이터를 보호할 생각이라면 휴면하지 말아야 한다.!!!!
    6. */
    7. unlock_kernel();
  9. seq 락

    • 공유 데이터를 읽거나 쓰기 위한 아주 간단한 메커니즘을 제공.
    • 많은 Reader와 적은 Writer가 있는 경우를 위한 매우 가볍고 확장성이 좋은 락이다.(  Writer를 선호, 다른 Writer가 없을경우 항상 락을 잠글 수 있다. )
  10. 선점의 비활성화

    • 커널이 선점형이므로 새로 실행되는 태스크가 선점된 태스크와 동일한 위험구역에 진입할 수 있다 .그러므로 커널 코드는 스핀락을 사용하여 선점 불가능한 코드 구역을 표시해야 한다.
    •  하나의 변수가 프로세서에 고유한 변수라면 락이 필요치 않게 되지만 프로세서간 선점으로 인해 유사 동시적으로 접근될 수 있다.

      1. preempt_disable();
      2. /* 선점이 비활성화됨 ..*/
      3. preempt_enable();
      • 커널 선점을 비활성하여 한다.
  11. 오더링과 배리어

    • 프로그램 코드에 정의된 순서대로 행해야 하는 경우가 있다.

      • 하드웨어를 가지고 작업할 때는 어떤 읽기 작업이 다른 읽기나 쓰기 작업 이전에 행해져야 한다는 식의 요구조건.
    • 컴파일러와 프로세서 모두가 최적화를 위해 읽기/쓰기(인텔x86예외) 명령의 순서를 마음대로 뒤바꿀수 있기 때문에 별도의 방법이 존재한다.

      • 읽기와 쓰기 명령의 순서를 바꾸는 프로세서들은 명령의 순서 요구조건을 만족시킬 수 있는 기계어 명령을 제공한다.
      • 컴파일러에게 특정 지점에서는 명령어의 순서를 바꾸지 말도록 지시할 수도 있다. 배리어(Barrier) !!
    1. a = 1;
    2. b = 2;

      // 프로세서는 a보다 먼저 b에 새로운 값을 저장할 수도 있다. 컴파일러와 프로세서는 a와 b 사이에 어떠한 관련성이 있음을 알 수 없다.

    3. // a와 b사이에 명백한 연관이 존재하지 않기 때문에 재배열이 발생한다.
    4. a = 1;
    5. b = a;
    6. // a와 b사이에 명확한 데이터 의존성이 존재하기 때문에 재배열하지 않는다. a와 b사이에 명확한 데이터 의존성이 존재.
    •  barrier() 함수를 통해 컴파일러가 로드와 스토어 명령을 최적화하는 것을 방지 할 수도 있다.
  12. 요약

    1. 원자적 연산 : 동기화를 담보하는 가장 단순한 방법.
    2. 스핀락 : 해당 락에 오직 하나의 보유자만이 존재할 수 있는 가벼운 락으로 경쟁이 발생하면 바쁜 대기를 수행한다.
    3. 휴면락 : 세마포어와 완료변수, seq락
    4. 경쟁상태를 유발하지 않으면서 훌륭한 동기화를 보장할 수 있는 커널코드를 작성하자!! 심플하게~!

이 글은 스프링노트에서 작성되었습니다.

커널 동기화 기초

from Study/System 2009/02/15 16:02 view 27740
  1. 커널 동기화 ?

    • 메모리를 공유하는 응용 프로그램은 항상 동시적인 접근으로부터 공유된 자원을 보호해야 한다.
    • 다수의 실행중인 스레드가 동시에 데이터를 변경할 경우 다른 스레드가 변경한 부분을 또 다른 스레드가 잘못 덮어써버릴 가능성이 있다.
    • 멀티프로세싱, 선점형 스케줄링 환경에서는 다양한 동시성 문제가 발생할 수 있다.


  2. Critical Region(위험구역) and Race Condition (경쟁 상태)

    • 위험구역이란 공유된 데이터를 접근하여 조작하는 코드 부분을 가리킨다. 원자적 실행을 보장해야 한다.
    • 경쟁상태란 스레드들이 위험구역에 들어가기 위해 경쟁하는 상태.


  3.  락킹(Locking)

    • 한번에 오직 하나의 스레드만이 공유하는 자료구조를 조작할 수 있다는 것을 확실할 방법.
    • 특별한 구역에서 다른 스레드가 동작하고 있을 때 해당 자료구조를 접근하지 못하게 하는 방법.
    • 락은 동시성을 방지하여 경쟁상태로부터 큐를 보호할 수 있다.

      1. 스레드는 방에 들어서면서 방문을 잠근다. 공유 데이터의 사용이 끝나면 스레드는 자물쇠를 열고 방을 떠난다.
      2. 만약 다른 스레드가 방문에 도착했을 때 문이 잠겨져 있다면, 안에 있는 스레드가 문을 열고 나올 때까지 기다린 후에 방에 들어가게 된다.
      3. 스레드는 락을 잠그고, 락은 데이터를 보호한다.


  4. 동시성

    •  프로그램들이 선점되면서 스케줄링 된다는 사실에서 비롯된다. 어떤 프로세스가 위험지역에 있을 때 비자발적으로 선점돼 버리는 일이 발생할 수 있다.

      • 유사동시성(peudo-concurrency) - 실제로는 동시에 발생하지 않지만 서로 엇갈려서 실행돼 마치 동시에 실행되는 것과 같은 효과가 발생.
      • 진정한동시성(true-concurrency) - 대칭형 멀티프로세싱 시스템에서 두 프로세스는 정확히 가튼 시간에 하나의 위험지역에 진입 할 수 있다.
    • 커널에서의 동시성의 원인

      1. 인터럽트 - 비동기적으로 어느때나 발생하여 현재 실행중인 코드를 중단시킨다.
      2. softirq와 태스크릿 - 커널은 현재 동작중인 코드를 중단하기 위해 거의 언제라도 softirq나 태스크릿을 레이즈하거나 스케줄할 수 있다.
      3. 커널 선점 - 커널도 선점형이므로, 커널에 있는 한 태스크가 다른 태스크를 선점할 수 있다.
      4. 유저공간에서의 휴면과 동기화 - 커널의 태스크는 휴면할 수 있으며 따라서 스케줄러가 새로운 프로세스를 실행하게 된다.
      5. 대칭형 멀티프로세싱 - 2개 이상의 프로세서가 코드를 동시에 실행할 수 있다.
    • 동시성으로 인해 문제가 발생되는 경우 (락이 없다면..) : 경쟁상태가 발생

      1. 커널에서 어떤 자원을 조작하고 있는 도중에 인터럽트가 발생하여 같은 자원에 접근하는 경우.
      2. 커널이 공유 자원을 사용하고 있는 동안 커널 코드가 선점되는 경우.
      3.  위험지역을 실행하는 도중 커널 코드가 휴면하는 경우.
      4. 두 프로세서가 동시에 공유데이터에 접근하는 경우.


  5.  보호영역의 결정

    • 동시에 접근될 수 있는 모든 코드는 보호가 필요로 하므로, 사실 보호가 필요없는 코드를 먼저 찾아내는 법도 있다.

      1. 특정스레드에 로컬한 데이터가 있을 경우.( 로컬자동변수, 스택에서만 존재하는 자료구조들.. )
      2. 특정 태스크에 의해서만 사용되는 데이터.
    • 보호영역의 선정 ( 커널의 거의 모든 전역 데이터와 공유 데이터는 어떠한 형식으로든 동기화. )

      1. 데이터가 전역적인가 ? 다른 스레드가 이 데이터에 접근 가능한가?
      2. 데이터가 프로세스 컨텍스트와 인터럽트 컨텍스트간에 공유되는가?
      3. 데이터를 사용하는 도중 프로세스가 선점되는 경우, 새로 스케줄된 프로세스가 같은 데이터에 접근하는가?
      4. 현재 프로세스가 휴면(or 블록)하는 경우가 있는가? 만약 그렇다면 휴면(블록)시 공유 데이터가 어떤 상태에 놓이게 되는가?
      5. 다른 곳에서 이 데이터가 해제되지 않으려면 어떻게 해야 하는가?
      6. 이 함수가 다른 프로세서에서 호출되면 어떤 일이 벌어지는가?


  6. 데드락(Deadlock)

    • 어떠한 스레드도 더 이상 진행할 수 없는 상태

      • 각 스레드가 어떤 자원을 얻으려 대기하지만 이미 모든 자원의 락이 잡혀있을 때 발생한다. 모든 스레드가 서로에 대해 대기하므로 이미 잡고 있는 자원을 해제할 수도 없다.
    • 셀프 데드락(self-deadlock) 이란  어떤 스레드가 자기 자신이 이미 잡고 있는 락을 다시 얻으려 시도할려고 할때 발생.
    •  죽음의 포옹(deadly embrace) or ABBA 데드락 이란 2개의 스레와 2개의 락이 있는 경우 발생.

      • 스레드1이 락 A를 얻음 / 스레드2가 락 B를 얻음
      • 스레드1이 락 B를 얻으려 함 / 스레드2가 락 A를 얻으려 함
      • 스레드1이 락 B에 대해 대기 / 스레드2가 락 A에 대해 대기
    • 데드락 방지

      1. 중첩된 락은 반드시 같은 순서로 잠겨져야 한다. 죽음의 포옹을 방지.

        • 서로 다른 구조체를 보호하는 cat, dog, fox 라는 3개의 락이 있을 때 어떤 함수가 cat->dog->fox 순서로 접근을 하였다.
        • 다른 모든 함수 역시 같은 순서로 락들을 잠가야 한다.
      2. 기아현상(starvation)을 방지해야 한다. 코드가 종료하는가를 되짚어 봐야 한다. 어떠한 코드도 무한대기가 일어나서는 안된다.!

        • 락이 풀리기를 대기중인 스레드들은 적당한!! 시간에 락을 얻을 수 있어야만 한다.
      3. 같은 락을 두 번 잠그지 않아야 한다.( 리눅스에서는 재귀적 락을 제공하지 하는다. )
      4. 락은 최대한 단순하게 설계해야 한다.


  7. 경쟁과 확장성

    • 현재 사용되고 있는 어떤 락을 다른 스레드가 얻으려 하는 상황을 락경쟁(Lock Contention) 혹은 경쟁이라고 한다.

      • 경쟁이 심한 락일수록 시스템 성능 저하에 더 큰 영향을 미친다.
    • 확장성이란 어떤 시스템이 얼마나 잘 확장될 수 있는가를 가리킨다.
    • 락킹의 세세함(granularity) 이란 그 락이 보호하는 데이터의 크기를 고려하는 것을 의미한다.
    • 정확하지않은(coarse)락은 많은 양의 데이터, 전체 서브시스템의 자료구조를 보호하는 경우이다.

      • 락경쟁이 심할 경우 확장성의 저하로 이어진다.
    • 매우 촘촘한(fine grained)락은 매우 적은 양의 데이터, 큰 구조체에 속한 하나의 항목만을 보호한다.

      • 충분한 락 경쟁이 없는 경우 소모적인 부하로서 작용한다.

이 글은 스프링노트에서 작성되었습니다.

프로그래머 수행능력 - 개발자되기

from Info/Dev 2009/02/11 16:28 view 24990

/* 5년후엔 Level 3!! 이라고 외칠 수 있는 내가 되자.! */


  1. 컴퓨터 공학
    1. 자료구조 - Level 1 / STL을 쓰지않고 배열, 링크드리스트 정도는 사용하니..이정도는 무난하다. B-트리 AVL, RB-Tree 는 알고 있어도 ...ㅠ_ㅠ
    2. 알고리즘 - Level 1 / 기본적인 정렬, 서칭 코드는 사용할 수 있지 않을까..
    3. 시스템 프로그래밍 - Level 1 / 어셈블리를 읽지 못하므로 레벨 급강하.. 커널과 유저영역 가상메모리, 페이징에 대한 개념은 있다..
  2. 소프트웨어 공학
    1. 원시 코드 버전 제어 - Level 1 / SVN 비기너~ 뉴비!!
    2. 빌드 자동화 - Level 1 / 빌드과정을 수동(?)으로 오브젝트파일,라이브러리 링크,실행파일 만들기~!
    3. 테스트 자동화 - Level 0 / Automated unit tests 란 개념이 없다.. 그냥 마구 클릭, 경우의 수 테스트...
  3. 프로그래밍
    1. 문제 분석 - Level 1 / 사실 0.5 정도 되는게 맞을지도.. 내가 만든 함수를 누가 쓴적이 있던가...
    2. 시스템 분석 - Level 1 / 멀티 플랫폼, OS 간의 호환성 같은건 고려 해본적 없다.
    3. 의사 소통 - Level 0 / 굳 스펠링, 그래머 이 얼마나 어려운가.
    4. 파일 내 코드 조직화 - Level1 / 코드에 대한 레퍼런스는 만들지 않는다..ㅋ;; 그냥 그때 만들고.. 검색..ㅜ_ㅜ
    5. 파일 외부 코드 조직화 - Level 1 / 코드를 작성한 파일의 위치를 역할으로 나누기는 하는 모양새는 낸다.
    6. 소스트리 조직화 - Level 2 / 소스는 유틸, 라리브러리, 문서, 빌드에 필요한 파일 이런식으로 나누는게 속이 편하다...확실히!!
    7. 코드 가독성 - Level 2 / 변수하나 파일 하나에 이름을 붙일 때 1분은 생각해주는 게 1개월후의 나에대한 예의....
    8. 코드 방어성 - Level 1 / 코드에 대한 결점을 시뮬레이션 하고 예외처리 해주는 건 기본인데 왜 안하게 될까..
    9. 오류 처리 - Level 0 / 에러에 대한 처리는 Exit -_ㅡ;; 에러처리 전략을 짜놓고 전체적인 시스템을 조율하는 레벨은 도대체 언제쯤...
    10. IDE 활용 - Level 2 / 매크로는 사용 안할지라도 단축키는 무조건 프린터 해놓고 보면서 하는게 편한듯..
    11. API 활용 - Level 1 / Vast..막대한 In-depth Knowledge 라니 그냥 자주 사용 해 본정도로..ㅜㅜ
    12. 프레임워크 - Level 1 / 개발을 하려면 언제나 프레임워크 상에서.. Autor 는 제작자인가-_ㅡ...아~;;
    13. 요구사항 분석 - Level 1 / Complete 이런 단어는 왠지 부담스럼움.. 그냥 이런 요구사항이 맞나 확인 하는건 할 수 있다. 정말?
    14. 스크립트 활용 - Level 0 / shell scirpts 라도 알아야는데 .. Perl 도 알아야 는데 으.... 뭐해데..ㅜ_ㅜ..
    15. 데이터베이스 - Level 1 / ACID!! Atomic, Consistency, Isolation, Durable DB에 기본!! 이걸 기반으로 정규화 어쩌고 저쩌고...
  4. 경험
    1. 프로그래밍 언어 - Level 1 / 객체지향(사물-want) 와 SQL 은 나름 고민 해보았다.
    2. 플랫폼 - Level 1 / 메이저업체의 2-3 개 정도의 플랫폼의 경험을 가짐..
    3. 경력 - Level 0 / 1년이하;;
    4. 전문 분야 지식 - Level 1 / 최근에 한 번정도 씩 프로젝트를 가지면서 런칭은 해내는듯..유지보수는 ? ;;;
  5. 지식
    1. 도구 - Level 1 / 툴 사용은 언제나 즐겁다. 참조가 나름 되기도 한다. Scott Hanselman's power tools list 유명한가?;;
    2. 언어 - Level 1 / Erlang, Prolog 이런 언어는 이해하기가 어렵나..
    3. 코드기반 - Level 1 / 좀 생소하지만 코드 레이아웃의 기본지식과 시스템 구성의 어떻게 되있는지는 알고 있다.
    4. 신기술 - Level 1 / RSS 등록해놓고 기술은 보고 있다. 가끔식 관심 가는건 깔아보기도 하고.. 실행도 해보고 툴인가;;;
    5. 플랫폼 내부 - Level 1 / 윈도우, 리눅스 시스템을 공부하면서 플랫폼이란 하드웨어 위에 올려놓는 일종의 가상화 작업이라고...
    6. 책 - Level 0 / 마스터링 정규식 끄악~! -> 디자인 패턴 ->>>>>>>>>> 아트오브프로그래밍 ..... 왠지 넘사벽??
    7. 블로그 - Level 2 / RSS 50여개 등록해놓고 관심있는 글과 기사 내가 공부하고 있는 것들은 꾸준히 포스팅 중..불펌도 많이.;;;

이 글은 스프링노트에서 작성되었습니다.

리눅스커널 - 프로세스 스케줄링

from Note 2009/02/11 09:49 view 30291
  1. 프로세스 스케줄러란 ?

    • 다음번에 실행될 프로세스를 선택하는 커널 컴포넌트.
    • 시스템에 있는 실행 가능한 프로세스들에게 유한한 프로세서 시간을 분배해 주는 커널의 하위 시스템.
    • 리눅스와 같은 멀티태스킹 운영체제의 기본요소로 어느 프로세스를 실행할 것인가를 선택하는 동시에, 시스템의 성능을 최적화하고, 여러개의 프로세스가 마치 동시에 실행되고 있는 것과 같이 보이도록 해야 하는 책임을 갖는다.
    • 동작시나리오

      • 실행가능한 프로세스가 여럿 있다고 할 때 프로세서(CPU)를 최대한 이용하기 위해서는 항상 어떤 프로세스든 실행중이면 되는 것이다. 만약 시스템의 프로세서 수보다 많은 프로세스가 있을 경우 몇몇 프로세스는 실행될 수 없다. 이러한 프로세스들을 실행하기 위해 대기중이라는 상태가 있다.
    • 여러 프로세스 중에서 다음 프로세스를 선택하는 것이 스케줄러가 행하는 가장 중요한 작업이다.


  2. 멀티태스킹 운영체제

    • 협력형(cooperative) 멀티  태스킹과 선정형(preemptive) 멀티태스킹이 있다.
    • 리눅스는 다른 최신 운영체제 들과 마찬가지로 선점형 멀티태스킹을 지원한다.
    • 선점형 멀티태스킹은 프로세스가 언제 실행을 중지하고 또는 실행을 계속할 것인가를 바로 스케줄러가 결정.
    • 협력형 멀티태스킹은 프로세스가 자발적으로 실행을 중단할 때까지 중단되지 않는다. 자발적으로 자신을 중단시키는 일을 양보(yield)라 한다.


  3. I/O 중심 과 프로세서 중심 프로세스

    • I/O 중심 프로세스 들은 그 시간의 대부분을 I/O 요청을 보내고 기다리는 데 사용한다. 짧은 기간 동안만 실행가능하게 되는데, 왜냐하면 다른 I/O 요청에 의해 결국 또다시 대기 상태로 되기 때문이다.( 디스크, 키보드 )
    • 프로세서 중심 프로세스 들은 코드를 실행하는 데 대부분의 시간을 보낸다. 보통 선점되기 전까지 계속 실행되는데, 왜냐하면 I/O 요청 등으로 중단되지 않기 때문이다.
    • 스케줄러 정책은 항상 대립되는 두 가지 목표를 갖는다. 빠른 응답 시간(낮은 지연)과 높은 프로세스 처리량 을 만족시켜여 한다. 이러한 요구조건을 만족시기 위해 스케줄러는 다른 프로세스와의 공정성을 고려하여 실행시키기 가장 알맞은 프로세스를 결정한다.
    • 리눅스는 좋은 응답성을 제공하기 위해 프로세스 응답 시간에 최적화 되었기 때문에 프로세서 중심보다 I/O 중심 프로세스를 선호한다.


  4. 프로세스 우선순위

    • 스케줄링 알고리즘 중 가장 흔한 형태가 우선순위에 기반을 둔 알고리즘으로 리눅스 커널은 두 가지의 우선순위를 구현하고 있다.

      • 첫 번째는 nice값으로 -20에서 +19까지의 값을 갖는다.(기본값 0) 큰 nice값은 낮은 우선순위를 의미한다. 따라서 낮은 nice값을 갖는 프로세스들은 높은 nice값을 갖는 프로세스보다 먼저 실행된다. nice 값은 각 프로세스가 얼마나 타임슬라이스를 할당받는가를 결정하는 데도 사용된다. nice값이 -20인 프로세스는 최대 타임슬라이스를 할당받고, 19인 프로세스는 가장 작은 타임슬라이스를 할당받는다.
      • 두 번째는 실시간 우선순위로서, 0에서 99까지의 값을 갖는다. 또 모든 실시간 프로세스는 일반 프로세스보다 높은 우선순위를 부여받는다.


  5. 타임슬라이스

    • 정의 : 어떤 태스크가 선점되기 전까지 실행될 수 있는 시간이 얼마나 남았는가를 가리키는 값이다.( 좀 헷갈리는 구문.. 남아있는 시간? 아니면 선점시간? )
    •  타임슬라이스가 너무 길면 시스템의 InterActive한 성능을 떨어뜨려 프로세스가 동시에 수행되는 것처럼 느껴지지 않을 것이며, 너무 짧으면 프로세스간의 스위칭이 자주 일어나 자원낭비의 비효율성이 발생.
    • 높은 우선순위를 갖는 작업이 좀더 길게, 자주 수행되게 되는데 프로세스가 모든 타임슬라이스를 반드시 한번에 소비해야 하는 것은 아니다.


  6. 프로세스 선점 과정

    • 리눅스는 선점형 운영체제로 어떤 프로세스가 TASK_RUNNING  상태가 되면 커널은 이 해당 프로세스의 우선순위가 현재 실행중인 프로세스보다 높은가를 검사한다. 만약 높다면 스케줄러가 동작하여 실행할 새 프로세스를 선택한다. 또한 프로세스의 타임슬라이스가 0이 됐을 경우에도 프로세는 선점되고 스케줄러가 동작하여 실행할 새 프로세스를 고르게 된다.


  7.  스케줄링 정책 시나리오

    • 2개의 실행 가능한 프로세스, 텍스트 에디터와 비디오 인코더가 태스크가 있는 시스템을 가정해 보자!
    • 텍스트 에디터는 대부분의 시간을 사용자 입력을 기다리고 있으므로, I/O 중심 프로세스이다.
    • 비디오 인코더는 프로세스 중심이다. 인코더는 대부분의 시간을 원본 데이터에 비디오 코덱을 적용하는데 소비한다.
    • 텍스트 에디터는 InterActive 한 작업이므로 스케줄러는 텍스트 에디터에게 높은 우선순위와 긴 타임슬라이스를 주게 된다. 이로 인해 텍스트 에디터는 쓰고 남을 만큼의 타임슬라이스를 갖는다. 또한 텍스트 에디터는 높은 우선순위를 가지므로, 필요에 따라 비디오 인코더를 선점할 수 있다. 이렇게 하여 텍스트 에디터는 사용자의 키 입력에 즉각적으로 반응할 수 있다.
    • 비디오 인코더에게 손해인 것처럼 보이지만 텍스트 에디터는 잠깐 동안만 실행되므로 사실 비디오 인코더가 남은 시간을 거의 독점하여 사용할 수 있다.
    • 결과적으로 두 응용프로그램의 성능이 최대화 된다.


  8.  리눅스 스케줄링 알고리즘 - 이상적인 구현

    • 완전한 O(1) 스케줄링을 구현. 스케줄러의 알고리즘은 실행중인 프로세스의 개수에 무관하게 상수 시간안에 완료돼야 함.
    • 완변한 SMP 확장성을 가짐. 각각의 프로세스는 자신만의 락과 실행큐를 가짐.
    • SMP와의 상성을 개선할 것. ( 메모리는 프로세서보다 느리다. 단일 프로세서라도 메모리로부터 읽는 작업에 상당한 시간을 소비한다. SMP는 이를 더욱 악화시키는데, 한 번에 한 개의 프로세서만이 동일한 메모리에 접근 가능하기 때문이다. )
    • 자연스럽게 태스크를 특정 CPU와 연계시키고, 계속 그 CPU에서 실행 되도록 함. 오직 실행큐 크기의 밸런스를 맞추기 위해서만 태스크를 CPU에서 다른 CPU로 이동시켜야 함.
    • 좋은 InterActive 성능을 보장. 시스템에 많은 부하가 걸리는 경우에라도, InterActive 태스크에 대해 시스템이 즉각적으로 반응을 보여야 함.
    • 공평성을 유지. 어떤 프로세스도 일정 시간 이상 타임슬라이스 없이 존재해서는 안되며, 어떤 프로세스도 너무 많은 타임슬라이스를 할당 받아서는 안됨 .
    • 대부분의 경우인 1~2개의 실행가능한 프로세스가 있는 경우를 위해 최적화하되, 많은 프로세스가 있는 멀티프로세서로도 확장이 가능하게 함.


  9. 실행큐(Runqueue)

    • 스케줄러의 기본 자료구조. 각 프로세스를 스케줄하기 위한 주요 자료구조임.
    • 어떤 프로세서에 있는 실행가능한 프로세스의 목록으로, 한 프로세스당 하나의 실행큐가 존재한다.
    • 실행가능한 프로세스는 오직 하나의 실행큐에만 포함되어 있어야 한다. 중복포함 불가.
    • 여러 태스크가 실행큐를 동시에 조작하는 것을 방지하기 위해 스핀락이 사용되는데, 이것은 문을 열기 위한 열쇠와 같다. 문에 처음 도착하는 태스크는 손잡이에 꽃힌 열쇠를 빼낸 다음 문을 담고 잠근다. 안에서 문을 잠근 상태 열쇠는 없다.안에 있는 태스크가 문을 열고 나와서 열쇠를 반납할 때 까지 기다려야 한다.
    • Spinning 상태가 발생하게 된다. 열쇠의 반납여부를 검사하기 위해 루프를 돌고 있기 때문이다.


  10. 우선순위 배열( Queue 와 Bitmap을 가짐!! )

    • 실행큐는  2개의 우선순위 배열을 가진다. 활성(Active), 비활성(Expired) 의 성격을 지닌다. O(1) 스케줄링의 핵심 자료구조이다.
    • 각 우선순위 배열은 각 우선 순위 레벨마다의 실행가능 프로세스 큐를 가지고 있다. ( 각 큐에는 해당 우선순위 레벨의 실행가능한 프로세스 목록이 존재 )
    • 시스템의 가장 높은 우선순위의 실행가능 태스크를 효과적으로 찾아내기 위한 우선순위 비트맵을 포함하고 있다.


  11. 타임슬라이스의 재계산

    • 태스크의 타임슬라이스가 0이 됐을 때 타임슬라이스를 다시계산하기 위한 방법.
    • for ( each task on the system ) {

      recalculate priority

      recalculate timeslice

      }     

      • 시간이 오래 걸릴 가능성이 있다. 최악의 경우 시스템에 잇는 태스크의 수가 n이라면 O(n) 시간이 걸린다.
      • 재계산을 위해서는 태스크 목록과 각 프로세스 서술자를 보호하는 락을 사용해야 하므로, 높은 락 경쟁 상태가 발생할 수 있다.
      • 무작위적으로 발생하는 타임슬라이스의 재계산은 실시간 프로그램이 확정적 이어야 함에 장애 요인으로 작용할 수 있다.
      • 이 방법은 세련되지 않은 방법으로 커널2.6에서는 개선되어 있다.

































이 글은 스프링노트에서 작성되었습니다.

CDN에 대해서...

from Study/Network 2009/02/10 10:45 view 28313
  1. 경량으로 빠르고 안정적인 CDN 서비스를 제공하는 비트토런트 방식을 채택하여 네트워크 트래픽을 분산하고 네트워크에 연결된 다수의 컴퓨터들의 자원을 활용하는 N:1의 전송 시스템을 구축하여 파일을 분할, 암호화, 분산, 병렬 처리함으로써 안정성을 확보하는 그리드 딜리버리 기술을 적용한 VOD 솔루션.


  2. CDN ?  (Content Delivery Network: 콘텐츠 전송 네트워크)이란 인터넷에서 동영상이나 음악 스트리밍, 파일 다운로드 등 대용량 파일로 인한 트래픽 증가로 전송속도가 떨어질 때, 네트워크 주요 지점에 설치한 전용 서버에 해당 콘텐츠를 미리 저장하여 이용자 가까운 곳의 서버가 이를 내보내 인터넷 QoS(Quality of Service)를 유지시켜주는 서비스를 말한다.


  3. CDN의 장점
        - 콘텐츠 전송 속도 : middle mile을 경유하지 않으므로 전송속도 향상, 가입자망에서의 분배형 구조로 Traffic bursting시에도 전송속도 지연 방지.
        - 콘텐츠 전송의 안정성, 트래픽의 규모 : Traffic Overflow 방지, 스트리밍 서비스의 단절 해소.
        - 경제성 : QoS 향상, 웹호스팅 비용절감(공급자 측면), 시간비용 절감(수요자 측면), 관련 산업의 발전(네트워크 장비, 스토리지 등), middle mile에서의 트래픽 부담 완화
        - 네트워크 효율성 : CP간 설비 공유.
  4. CDN 관련 기술

    1. GLB(Global Load Balancing, Load Balancer)

      •  인 터넷의 여러 곳에 분산 배치된 서버들 중에서 이용자에게 최상의 서비스를 제공할 수 있는 서버를 선정해 서비스를 연결하는 기술로, 최상 위치의 서버에 장애가 일어났을 경우에도 차상위 서비스를 할 수 있는 서버로 우회 연결하여 장애를 해소시키게 된다. 자체 장애에 대비해 서로 다른 네트워크상에 이중으로 배치하게 된다.
      • GLB.jpg
    2. 동기화 기술(synchronization)

      •  콘 텐츠 변경시 ISP별로 분산된 서버에 이를 즉각적으로 반영하여 사용자들이 한꺼번에 동일한 내용의 콘텐츠를 전송 받을 수 있도록 하는 기술로 분산된 서버의 어느 하나에도 파일의 유실이나 오류가 없도록 한다. 이러한 기술은 특히 프로그램 등 S/W의 업데이트에 유용하게 활용.
        SYN.jpg
    3. Grid Delivery

      •  단기간 급증하는 트래픽 처리를 위해 콘텐츠 업계가 활용할 수 있는 방법은 첫째, 단기간에 다량의 서버와 네트워크를 투입하는 방법, 둘째, P2P 기술을 활용해 트래픽을 분산시키는 방법, 셋째, 일정 트래픽까지는 서버를 활용하되 그 이상에 대해서는 P2P 기술을 활용하는 혼합적 방법이 있다.
      • Grid Delivery는 이 중 세 번째에 가까운 이용자 컴퓨터를 활용하는 기술이다. 즉, 콘텐츠를 전송할 때 이용자의 컴퓨터를 각각 작은 서버로 활용, 이용자가 콘텐츠를 다운로드하면서 다른 이용자에게 콘텐츠를 전송하도록 고안된 것으로서, 이용자가 콘텐츠의 이용자인 동시에 전송자가 된다. P2P와는 콘텐츠 사업자가 이용자의 컴퓨터 일부를 제어할 수 있도록 한다는 점이 다르다. 이 기술은 유휴자원의 활용 측면에서는 장점이 많지만 이용자의 컴퓨터를 타인이 어느 정도 선에서 재량적으로 활용한다는 점에서 불쾌감을 줄 수도 있으나, 최근 선진국을 중심으로 점차 확산되고 있다. 미국에서는 Verisign이 이 기술 전문업체인 Kontiki를 인수하여 새로운 형태의 CDN 서비스를 준비하고 있으며, 국내에서는 나우콤이 자사의 웹스토리지 서비스를 활용하여 이용자들을 그리드팜으로 묶어 CDN의 서비스 품질과 안정성을 구현하겠다는 전략을 세우고 있다. 상기한 기술 외에도, 인기 콘텐츠와 비인기 콘텐츠를 실시간으로 파악, Local 서버에서는 인기콘텐츠만 서비스하도록 하여 스토리지를 효율적으로 활용하게 하는 File System Manager 기술이나, 불법 다운로드를 방어하는 콘텐츠 보호 기술, 서비스 종류에 따라 서버를 구분(동영상방송서버, 이미지캐시서버, 다운로드서버 등)하여 구축하는 기술 등이 CDN에 있어 주요기술이라고 할 수 있다.
  5. 서비스 분야

    1. 다운로드 서비스: 게임 설치파일, 패치파일, 네비게이션 프로그램 등 대용량 파일을 빠르고 안정적으로 전송해 주는 서비스로 이용자들이 한꺼번에 몰리더라도 원활하게 콘텐츠의 전송을 하는 것이 목적임.
    2. 스트리밍 서비스: 온라인 교육, VOD, 인터넷방송, UCC, 실시간 인터넷 중계 등에서 화면 끊김이나 버퍼링을 최소화하는 서비스.
    3. 캐싱 서비스: 이미지가 많은 쇼핑몰, 포털, 게임 등 다수의 캐시서버를 이용한 트래픽.
    4. 분산처리를 통해 웹사이트 로딩 속도를 향상시키는 서비스를 말함. 콘텐츠의 빠른 전송에 유용하고 이미지가 많은 쇼핑몰이나 포털, 게임 등에서 안정적인 이미지 유지가 목적.

      CDNService.jpg



관련기사


참고자료

  •  정보통신정책 제 20 권 1호 통권 431호 - CDN 서비스의 현황 및 이슈 (연구원 홍 범 석, 연구원 김 태 현)CDN1.PDF

이 글은 스프링노트에서 작성되었습니다.