------

[ AD ] Port Monitor ( Try to use a Best WebSite Monitoring Tool )

------
전체에서 Integer 4bytes만 복사 === 나머지 길이
전체에서 Integer 4bytes만 복사
LRESULT CChatClientDlg::OnSocketMsg( WPARAM wParam , LPARAM lParam )
{

	SOCKET sock = (SOCKET)wParam;

	//에러체크
	int nError = WSAGETSELECTERROR( lParam );
	if( 0 != nError )
	{
		OutputMsg( "[에러] WSAGETSELECTERROR : %d ", nError );
		m_AsyncSocket.CloseSocket( sock );
		return false;
	}
	
	//이벤트 체크
	int nEvent = WSAGETSELECTEVENT( lParam );

	switch( nEvent )
	{
	case FD_READ:
		{
			int nRecvLen = recv( sock , m_szSocketBuf + m_nRestRecvLen , MAX_SOCKBUF , 0 );
			if( 0 == nRecvLen )
			{
				OutputMsg("[CLOSE] 클라이언트와 연결이 종료 되었습니다.");
				m_AsyncSocket.CloseSocket( sock );
				return false;
			}
			else if( -1 == nRecvLen )
			{
				OutputMsg("[ERROR] recv 실패 : %d " , WSAGetLastError() );
				m_AsyncSocket.CloseSocket( sock );
			}

			m_nRestRecvLen += nRecvLen;

			//패킷길이의 크기보다 적게 들어왔다면
			if( m_nRestRecvLen < 4 )
				return true;
			//패킷의 길이를 얻어온다.
			int nMsgLen = 0;
			char* pCurrent = m_szSocketBuf;
			CopyMemory( &nMsgLen , pCurrent , 4 );
			//하나의 완전한 패킷을 모두 받았다면.. 
            while( nMsgLen >= m_nRestRecvLen )
			{
				ProcessPacket( m_szSocketBuf , nMsgLen );
//				nMsgLen -=m_nRestRecvLen;
				m_nRestRecvLen -= nMsgLen;
				if( m_nRestRecvLen <= 0 )
					break;
				pCurrent += nMsgLen;
				CopyMemory( &nMsgLen , pCurrent , 4 );
			}
			MoveMemory( m_szSocketBuf , pCurrent , m_nRestRecvLen );

			break;
		}
	case FD_CLOSE:
		{
			OutputMsg("[CLOSE] 클라이언트 접속 종료 : SOCKET(%d)", sock );
			m_AsyncSocket.CloseSocket( sock );
		}
		break;
	}
	return true;

}



5,6번째 자리 복사 하면 -===> 명령어 자리
::ProcessPacket( char* pRecvBuf , int nRecvLen )
{
	unsigned short usType;
	CopyMemory( &usType , pRecvBuf + 4 , 2 );
	switch( usType )
	{
	case PACKET_CHAT:
		{
			Packet_Chat* pChat = (Packet_Chat*)pRecvBuf;
			OutputMsg("[%d] : %s", pChat->s_sIndex , pChat->s_szChatMsg );
		}
		break;
	case PACKET_MOVE:
		{
			OutputMsg("[Move]");
		}
		break;
	default:
		OutputMsg("[ERROR] 정의되지 않은 메시지 도착");
		break;
	}

}


'온라인게임 > vc++' 카테고리의 다른 글

IO Completion Port  (0) 2010.10.06
vs 2010 팁 ( visual studio 추가 설치 파일 )  (0) 2010.10.05
숭실대학교 미디어대학원 컴퓨터그래픽스 Magic  (0) 2010.10.05
MFC 표기법  (0) 2010.10.05
기능  (0) 2010.10.05
http://magic.ssu.ac.kr/07_magic/introduction.html


2. 석박사, 학부생 연구원 수시 모집
       석박사 과정생에게는 논문 발표 여부와는 별도로
       1회 이상의 해외 단기연수 기회(미국 SIGGRAPH 원칙)를 제공합니다.

       자세한 내용은 김동호 교수(02-920-0721 또는 dkim@ssu.ac.kr)와
       상담 바랍니다.

숭실대학교 미디어대학원 컴퓨터그래픽스 Magic (김동호 교수님) 연구실 입니다.

2004년 3월 정식 출범한 Magic 연구실은 Media Art, Graphics, Interactive Contents 의 약자로
다양한 미디어분야에서 필요한 핵심기술을 연구하고 있습니다.

본 연구실은 Real-Time Rendering with Graphics Hardware분야를 중점 연구하여
이것을 이용한 Interactive Art, Game Graphics, Web3D 등등의 여러 분야에서 다양한 활동을 하고 있습니다.

또한 Computer Graphics의 다양한 분야를 연구함으로 국내외적으로 그래픽스 분야의 선두 연구실로 자리매김하고 있습니다.


 
nMFC의 표기법
n헝가리안 표기법을 사용한다.
n클래스
n모두 C로 시작한다.
n여러 단어가 하나의 클래스 이름일 경우
n단어별로 첫 글자를 대문자로 표기한다.
n멤버 변수
nm_로 시작하고,
n멤버 함수
n대문자로 시작한다.
n전역 함수
 n Afx라는 접두어가 붙는다.
1. DC얻기 

  CClientDC dc(this); 

 


2. Client 영역 구하기 

  GetClientRect(&rect); 

  WM_SIZE 메시지발생후 cx,cy 사용 

 


3. 문자열 사각형안에 그리기 

  pDC->DrawText(문자열,사각형,Style); 

  Style: DT_BOTTOM - 문자열을 사각형 맨아래줄에배열 반드시 DT_SINGLELINE과 함께사용 

        DT_CENTER - 문자열을 가로중앙에 배치 

        DT_VCENTER - 문자열을 세로중앙에 배치 

        DT_LEFT,RIGHT - 문자열을 좌,우로 배치 

        DT_SINGLELINE - 문자열을 한줄로만 쓴다 

 


4. Brush 사용법 

  CBrush brushname(RGB(red,green,blue)); //브러쉬 생성 

  CBrush *oldBrush=pDC->SelectObject(&brushname); //이전Brush 저장, 새로운 Brush 선택 

  pDC->SelectObject(oldBrush); //원래의 브러쉬로 반환 

 


5. Pen사용법 

  CPen pen(Pen Style,RGB(red,green,blue)); //브러쉬생성 

//Style: PS_SOLID,PS_DASH,PS_DOT,PS_DASHDOT,PS_GEOMETRIC,PS_COSMETRIC - 펜종류 

        PS_ENDCAP_ROUND,PS_ENDCAP_SQUARE - 펜끝을 둥글게,각지게 설정 

  CPen *oldPen=pDC->SelectObject(&pen); //이전Pen저장, 새로운 Pen설정 

  pDC->SelectObject(oldPen); //펜반환 

 


6. 화면다시그리기 

  View Class에서 - Invalidate(TRUE) : 화면을 지우고다시그린다 

                    Invalidate(FALSE) : 화면을 덮어씌운다 

  UpdateAllViews(NULL);  // Doc Class에서 View 의 OnDraw 호출 

  RedrawWindow(); 

 


7. 메시지,함수 수동으로 넣기 (EX)버튼클릭함수넣기 

  헤더파일의 AFX_MSG_MAP 부분에 함수를 정의 

  EX) afx_msg void funcName(); 

  .cpp파일의 AFX_MSG 부분에 메시지를 추가한다 

  EX) ON_BN_CLICKED(ID_NAME,funcName)... 

  ID 등록:  View 메뉴의 Resource Symbol 에 들어가서 메뉴 ID 를 등록해준다.. 

  .cpp파일의 맨아래에서 함수를 정의한다 

  EX) void CClass::funcName() { ... } 

 


8. 마우스커서 바꾸기 

  리소스탭에서 커서를 그리고 저장한뒤 ID값은 준다음 

  SetCapture(); //커서의입력을 클라이언트영역을 벗어나더라도 받아낸다 

  SetCursor(AfxGetApp()->LoadCursor(nIDResource)); 

  //APP클래스의 LoadCursor View의 SetCursor 사용 

  ReleaseCapture(); //SetCursor()상태를 해제한다 

 


9. 색상표 사용하기 

  CColorDialog dlg; 

  if(dlg.DoModal()==IDOK) //Dialog 를 띄운후 OK버튼을누르면 실행할부분 

  MemberFunc: GetColor() //선택된 색상을 받아온다 return 형은 COLORREF 형 

 


10. 팝업메뉴 만들기 

  CMenu menu; //메뉴 객체생성 

  CMenu *pmenu; //메뉴 포인터생성 

  menu.LoadMenu(IDR_MAINFRAME); //메뉴를 불러온다 

  pmenu=menu.GetSubMenu(3); //메뉴의 3번째 메뉴를 가져온다 

  menu.CheckMenuItem(ID_MENU,m_kind==ID_MENU ? MF_CHECKED : MF_UNCHECKED); 

  //메뉴 체크하기 (메뉴 ID, ID 체크조건) 

  pmenu->TrackPopupMenu(TPM_LEFTALIGN,point.x,point.y,this)  //(TMP_Style,x좌표,y좌표,hWnd) 메뉴 띄우기 

 


  *주의사항* 

    [안내]태그제한으로등록되지않습니다-OnContextMenu(CWnd* pWnd, CPoint point)  //여기서 point 는 스크린 기준이고, 

    OnRButtonDown(UINT nFlags, CPoint point)  //여기서 point 는 클라이언트 기준이다! 

 


11. 클라이언트 포인터를 스크린 포인터로 변경 

  ClientToScreen(&point); 

 


12. 그림판기능 

         if(m_flag==FALSE)  return;   //m_falg=그리기 기능 참,거짓설정  그리기 아니면 빠져나간다 

        CClientDC dc(this); 

        CPen myPen(PS_SOLID,m_width,m_color); 

        CPen *pOldPen=dc.SelectObject(&myPen); 

        switch(m_shape) 

        { 

        case ID_FREELINE: //자유선그리기 

                dc.MoveTo(m_oldpt.x,m_oldpt.y); //지난포인터부터 

                dc.LineTo(point.x,point.y); //새포인터까지 그린다 

                break; 

        case ID_RECT: //사각형그리기 

                dc.SetROP2(R2_NOTXORPEN); 

                dc.Rectangle(m_spt.x,m_spt.y,m_oldpt.x,m_oldpt.y);  //지워지는 효과 

                dc.Rectangle(m_spt.x,m_spt.y,point.x,point.y); //그려지는 효과 

                break; 

        case ID_ELLIPSE: //원그리기 

                dc.SetROP2(R2_NOTXORPEN); 

                dc.Ellipse(m_spt.x,m_spt.y,m_oldpt.x,m_oldpt.y);  //지워지는 효과 

                dc.Ellipse(m_spt.x,m_spt.y,point.x,point.y); //그려지는 효과 

                break; 

        case ID_LINE: //선그리기 

                dc.SetROP2(R2_NOTXORPEN); 

                dc.MoveTo(m_spt.x,m_spt.y); //시작점부터 

                dc.LineTo(m_oldpt.x,m_oldpt.y); //지난점까지 그은선을 지운다 

                dc.MoveTo(m_spt.x,m_spt.y); //시작점부터 

                dc.LineTo(point.x,point.y); //새로운점까지 그린다 

                break; 

        } 

        m_oldpt=point;  //바로이전값 보관 

        dc.SelectObject(pOldPen); //펜 반환 


13. MessageBox 

  AfxMessageBox() -> 전역함수를 이용하영 메세지 박스를 출력한다.   //어디서든지 사용할수 잇다 

  int CWnd::MessageBox("메세지","창제목","아이콘|버튼(상수값)");   //View클래스에서 사용한다 

  아이콘 상수값  MB_IC[안내]태그제한으로등록되지않습니다-xxONERROR, MB_ICONWARNING, MB_ICONQUESTION,MB_ICONINFOMATION 

                MB_SYSTEMMODAL //시스템모달 대화창 닫기전에 다른작업 못함 

                MB_APPLMODAL //응용모달 

  버튼 상수값    MB_OK, MB_OKCANCEL, MB_YESNO 

 


14. OS 컨트롤 

        ExitWindowEx(EWX_SHUTDOWN,NULL); //Shut Down 

        ExitWindowsEx(EWX_FORCE,0); //강제종료 

        ExitWindowsEx(EWX_LOGOFF,0); //로그오프 

        ExitWindowsEx(EWX_POWEROFF,0); //Shut Down -> Turn Off 

        ExitWindowsEx(EWX_REBOOT); //Shut Down -> Reboot 

 


15. DialogBox 메시지 교환 

        UpdateData(FALSE); // 컨트롤에 멤버변수의 내용을 표시해준다 

        UpdateData(TRUE);  // 컨트롤 내용을 다이얼로그 클래스의 멤버변수로 저장 

 


16. 자료변환 

        atoi,itoa - int <=> ASCII(char) 변환 

        str.Format(" %d %d",x,y); // int형을 문자열로 변환 

        atol,ltoa - ASCII <=> long 변환 

        atof - ACSII => float 변환 

        fcvt,gcvt  - 실수를 text로 변환 

        LPtoDP, DPtoLP - 장치좌표 <=> 논리좌표 변환 

 


17. CEdit Class 사용하기 

  CEdit e_str.SetSel(int StartChae, int EndChar); //처음문자부터 마지막까지 블록 지정 

  CEdit e_str.GetSel(int SChar,int EChar); //블럭 지정한 처음문자와 마지막문자 받기 

  CString str=m_str.Mid(SChar,EChar-SChar); //블럭지정한 부분을 가져온다 


18. 컨트롤과 자료교환 

  SetDlgItemText(컨트롤 ID,문자열) //컨트롤에 문자열을 넣는다 

  GetDlgItemText(컨트롤 ID,문자열) //컨트롤의 내용을 문자열에 넣는다 

  GetDlgItem(컨트롤 ID); //컨트롤의 주소를 가져온다 


19. 상태바조작 

  CMainFrame 생성자 위에 

  static UINT indicators[] = //이안에 새로운 ID를 넣고 그 ID의 갱신핸들러를 만든다음 코딩 

  pCmdUI->SetText("표시할내용“); 

 


20. 수동으로 Bitmap 컨트롤 사용하기 

  CStatic bitmap; //bitmap 컨트롤변수 

  bitmap.SetBitmap(CBitmap m_bitmap); //컨트롤에 비트맵지정 

  GetDlgItem(IDC_BITMAP)->ShowWindow(SW_SHOW,HIDE);  // 그림을 보이거나 숨긴다. 

   

21. 응용프로그램 실행하기 

  WinExec("프로그램경로“,SW_SHOW,HIDE); //응용프로그램실행,경로는 \\로 구분한다 

 


22. Bitmap 사용하기 

  CBitmap bitmap.LoadBitmap(IDC_BITMAP); //비트맵객체에 비트맵지정 

  CDC memDC; //그림그릴 메모리DC생성 

  MemDC.CreateCompatibleDC(pDC); //화면 DC와 메모리 DC 호환 생성 

  CBitmap *pOldBitmap=MemDC.SelectObject(&m_bitmap); //메모리에 그림을그린다. 

  pDC->BitBlt(int x, int y,int Width, int Height, CDC* pSrcDC, int xSrc, int ySrc, DWORD dwRop); 

//BitBlt(그림x좌표,그림y좌표,그림넓이,그림높이,그림그려진메모리DC,그림시작x좌표,그림시작y좌표,스타일); 

  pDC->StretchBlt( int x, int y, int nWidth, int nHeight, CDC* pSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop ) 

//StretchBlt(그림x좌표,그림y좌표,그림넓이,그림높이,그림그려진메모리DC,그림x좌표,그림y좌표,메모리그림넓이,메모리그림높이,스타일); 

MemDC.SelectObject(pOldBitmap); // 메모리DC반환 

 


23. Font 바꾸기 

  CFontDialog dlg; //폰트다이얼로그 생성 

  LOGFONT m_logFont; //폰트받을변수선언 

  if(dlg.DoModal()==IDOK) //폰트다이얼로그표시 

  {dlg.GetCurrentFont(&m_logFont)} //선택된 폰트받기 

  OnDraw() 

   CFont newFont,*pOldFont; //폰트 객체 만들기 

   newFont.CreateFontIndirect(&m_logFont); //폰트 생성 

   pOldFont=(CFont *)pDC->SelectObject(&newFont); //폰트 선택 

   OnCreate() 

   CClientDC dc(this); //DC 생성 

   CFont *pFont=dc.GetCurrentFont();        //클라이언트 영역의 폰트를 

   pFont->GetLogFont(&m_logFont); //로그폰트 멤버값으로 지정 

 


24. Font 만들기 

         LOGFONT logfont; //폰트를 만든다 

        logfont.lfHeight=50;               //문자열 높이 

        logfont.lfWidth=0;                 //너비 

        logfont.lfEscapement=0;            //문자열기울기 

        logfont.lfOrientation=0;             //문자개별각도 

        logfont.lfWeight=FW_NORMAL;     //굵기 

        logfont.lfItalic=TRUE;             //이탤릭 

        logfont.lfUnderline=TRUE;  //밑줄 

        logfont.lfStrikeOut=FALSE; //취소선 

        logfont.lfCharSet=HANGUL_CHARSET; //필수 

        logfont.lfOutPrecision=OUT_DEFAULT_PRECIS;                

        logfont.lfClipPrecision=CLIP_DEFAULT_PRECIS;      //가변폭폰트 고정폭폰트 

        logfont.lfPitchAndFamily=DEFAULT_PITCH|FF_SWISS; //글꼴이름 

        strcpy(logfont.lfFaceName,"궁서체"); 

        CClientDC dc(this); 

        CFont newFont; //폰트객체생성 

        newFont.CreateFontIndirect(&logfont); //폰트지정 

        CFont *pOldFont=dc.SelectObject(&newFont); //폰트선택 

        dc.TextOut(100,100,m_text); 

        dc.SelectObject(pOldFont); //폰트반환 

 


25. Font 만들기 2 

  CFont newFont; 

  newFont.CreateFont( int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename ); 

 CFont *pOldFont=dc.SelectObject(&newFont); 

 


26. ComboBox 사용하기 

  CComboBox combo; //콤보박스 선언 

  combo.Create( DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID ); 

  //Style - WS_CHILD|WS_VISIBLE 

  int n=combo.GetCurSel(); //선택된 아이템의 index를 가져온다 

  combo.AddString("문자열"); //문자열을 추가한다 

  combo.GetLBText(n,str); //n번째 아이템을 str에 저장 

 


27. Spin 사용하기 

  Spin은 바로앞의 Tab Order에 따라 붙는다 

  m_spinr.SetRange(1900,3000); //스핀 범위 지정 

  m_spinr.SetPos(m_nYear); //스핀 위치 지정 

 


28. CTime사용하기 

  CTime time; //시간객체생성 

  time=CTime::GetCurrentTime(); //현재시간을 저장 

  time.GetYear(),time.GetMonth();,time.GetDay(),time.GetHour(),time.GetMinute(),time.GetSecond() 

 


29. CListBox 메소드 

  AddString("문자열");             //리스트에 문자열 추가 

  DeleteString(index);             //리스트에서 항목 삭제 

  GetCount()                     //전체 항목 갯수를 얻는다. 

  GetSelcount()                   //선택된 항목 갯수 리턴 

  GetSel()                       //선택된 것인지 아닌지를 리턴한다 -> 양수 = TRUE , 음수 => FALSE 

  GetText(int index,문자열변수)     //index 번째 문자열을 문자열 변수에 넣는다 

  FindStringExact(문자열)          //지정 문자열의 index 값 리턴 -> 없으면 리턴값 LB_ERR 반환 

  FindString("a")                 //"a"로 시작하는 항목을 모두 찾는다. 

  ResetCountent()                 //모든 내용을 지운다. 

 


30. 파일입출력 

 프로젝트생성시 Step4 => Advanced => 저장파일확장자지정 

 .h 파일에       DECLARE_SERIAL(CSawon) //이 클래스를 저장,로드가능한 클래스로 쓰겟다는 선언 

 .cpp 파일에     IMPLEMENT_SERIAL(CSawon,CObject,1) //이거를 해야 저장이 가능하다 

void CFileioDoc::Serialize(CArchive& ar) 

        if (ar.IsStoring())  //저장하기 

        {ar< 

        else    //열기 

        {ar>>m_shape; //불러올걸 쓴다. 읽을때도순서대로읽어야한다} 

 


31. MicroSoft FlexGrid 사용하기! 

        CMSFlexGrid m_Grid; //FlexGrid 컨트롤 변수 

        CString strTitle[]={"고객코드","고객성명","고객포인트","신장","몸무게","고객등급","BMT지수","판정결과"}; 

        // Grid 의 제목에 넣을문자배열 

        int Width[]={900,900,1100,800,800,900,1000,900}; 

        // Grid 의 열넓이 지정할 배열 

        m_Grid.SetRows(m_cnt+2); //전체행수 지정 

        m_Grid.SetCols(8); //전체열수 지정 

        m_Grid.Clear(); //지우기 

        m_Grid.SetFixedCols(0); //고정열은 없다. 

        m_Grid.SetRow(0); // 행선택 

        for(int i=0;i<=7;i++) 

        { 

                m_Grid.SetColWidth(i,Width[i]); //열 넓이 설정 

                m_Grid.SetCol(i); //열 선택 

                m_Grid.SetText(strTitle[i]); // 선택된행, 선택된열에 Text 를 넣는다 

        } 

 


32. 4대 Class간 참조 

//각각 헤더파일 include 

#include "MainFrm.h" //메인프레임 헤더파일 

#include "ClassDoc.h"   //Doc클래스 헤더파일 

#include "ClassView.h" //View를 include 할때는 반드시 Doc 헤더파일이 위에잇어야한다 

#include "Class.h" //APP Class 의 헤더파일 

 


void CClassView::OnMenuView() //뷰클래스 

        CClassApp *pApp=(CClassApp *)AfxGetApp();   //View -> App
        CMainFrame *pMain=(CMainFrame *)AfxGetMainWnd();  //View -> MainFrm 

        CClassDoc *pDoc=(CClassDoc *)pMain->GetActiveDocument(); //View -> MainFrm -> Doc 

        CClassDoc *pDoc=(CClassDoc *)GetDocument();                     //View -> Doc 

 


 //MainFrame 클래스 

        CClassView *pView=(CClassView *)GetActiveView();  //MainFrm -> View 

        CClassDoc *pDoc=(CClassDoc *)GetActiveDocument();  //MainFrm -> Doc 

        CClassApp *pApp=(CClassApp *)AfxGetApp(); //MainFrm -> App 

 


//Doc 클래스 

        CClassApp *pApp=(CClassApp *)AfxGetApp(); //Doc -> App 

        CMainFrame *pMain=(CMainFrame *)AfxGetMainWnd(); //Doc -> MainFrm 

        CClassView *pView=(CClassView *)pMain->GetActiveView(); // Doc -> MainFrm -> View 

        CClassView *pView=(CClassView *)m_viewList.GetHead();      // Doc -> View 

 


//App 클래스 

        CMainFrame *pMain=(CMainFrame *)AfxGetMainWnd(); //App -> MainFrm 

        CClassView *pView=(CClassView *)pMain->GetActiveView(); //App -> MainFrm -> View 

        CClassDoc *pDoc=(CClassDoc *)pMain->GetActiveDocument(); //App -> MainFrm -> Doc 

 


33. ToolBar 추가하기 

  CMainFrame 으로 가서 멤버변수 추가 

        CToolBar m_wndToolBar1; 

  OnCreate 로 가서 다음 내용을 추가해준다 (위의 toolbar 부분을 복사하고 이름만 바꾸면 된다.3군데..) 

  if (!m_wndToolBar1.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP 

                | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || 

                !m_wndToolBar1.LoadToolBar(IDR_TOOLBAR1)) 

        { 

                TRACE0("Failed to create toolbar\n"); 

                return -1;      // fail to create 

        } 

 


  그 함수내에서 //TODO 아래에 내용추가..역시..복사해서 이름만 바꾸면 된다. 

        m_wndToolBar1.EnableDocking(CBRS_ALIGN_TOP|CBRS_ALIGN_BOTTOM); 

        //DockControlBar(&m_wndToolBar1);   <= 이부분 대신.. 

        이거를 넣는다.. 

        CRect toolRect; //툴바 영역을 얻을 사각형 

        this->RecalcLayout(); //현상태의 Client 영역을 구해서 저장한다 

        m_wndToolBar.GetWindowRect(&toolRect); //툴바영역을 저장한다 

        toolRect.left+=1; //사각형의 왼쪽을 1Pixel 줄인다 

        DockControlBar(&m_wndToolBar1,AFX_IDW_DOCKBAR_TOP,&toolRect); //ToolRect에 툴바를 붙인다 

        return 0; 

 


34. ToolBar에 ComboBox붙이기 

        CComboBox m_combo; //객체생성 

        ID 등록 => view 메뉴 => resource symbol => new => ID_COMBO 

  oncreate 에 내용 추가 (콤보를 만들고 표시하는 내용) 

        m_wndToolBar.SetButtonInfo(10,IDC_COMBO,TBBS_SEPARATOR,150);  

        //툴바의 10번째버튼을 편집한다 

        CRect itemRect; //콤보를넣을 사각형을 만든다 

        m_wndToolBar.GetItemRect(10,&itemRect); //툴바의 10번째 버튼을 사각형에 넣는다 
        itemRect.left+=5; //앞여백 

        itemRect.right+=5; //뒤여백 

        itemRect.bottom+=100; //콤보가열릴 공간확보 

        m_combo.Create(WS_CHILD|WS_VISIBLE|CBS_DROPDOWN,itemRect,&m_wndToolBar,IDC_COMBO); 

        //콤보박스를 툴바에 붙여준다 

        m_combo.AddString("이름"); //내용추가 

        m_combo.SetCurSel(0); //셀 선택 

 


35.  Toolbar에 수동으로넣은 ComboBox 사용하기 

  afx_msg void [안내]태그제한으로등록되지않습니다-xxOnSelectCombo(); //원형 

  ON_CBN_SELCHANGE(IDC_COMBO,[안내]태그제한으로등록되지않습니다-xxOnSelectCombo) //메세지맵에 추가 

        CMainFrame *pMain=(CMainFrame *)GetParent(); //메인프레임 주소참조 

        CComboBox *pCom=(CComboBox *)(pMain->m_wndToolBar.GetDlgItem(IDC_COMBO)); 

        //콤보박스의 주소를 가져온다, 접근할 때 메인프레임 -> 툴바 -> 콤보박스 의 순서로 가야한다 

        int n=pCom->GetCurSel(); //현재선택된 셀의 인덱스를 가져온다 

        if(n==CB_ERR) return; //선택된셀이 없으면 중지한다 

        CString str; 

        pMain->m_combo.GetLBText(n,str); //선택된셀의 Text를 가져온다 

 


36. UPDATE_COMMAND 사용하기 

        pCmdUI->Enable(TRUE); //버튼 활성화 

        pCmdUI->SetText((bAdd)?"취소":"신규"); //버튼의 text 설정 

        pCmdUI->SetCheck(TRUE); //버튼 체크 

 


37. 프로그램정보저장 

  CWinApp::GetProfileString(섹션명,항목명,기본값); // 함수를 사용한다. (문자열) 

  CWinApp::GetProfileInt(섹션명,항목명,기본값);  //불러올때사용 (숫자)  

  CWinApp::WriteProfileString(섹션명,항목명,값); //저장할때 사용 (문자열) 

  CWinApp::WriteProfileInt(섹션명,항목명,값); //저장할때 사용 (숫자) 

  //불러올때 사용할함수 

  void CMainFrame::ActivateFrame(int nCmdShow)  //프로그램 실행후 프레임생성될때 실행 

  //저장할 때 WM_DESTROY 메시지 사용 

 


38. 컨트롤바 표시하기 

        CMainFrame *pMain=(CMainFrame *)GetParent(); //MainFrame 주소가져오기 

        pMain->ShowControlBar(&pMain->m_wndToolBar,bTool1,FALSE); //툴바를 bTool2 에따라 보이고 감춘다 

 


39. Window 창크기,위치정보 저장하기 

MainFrame 의 WM_DESTROY 에 

        WINDOWPLACEMENT w; 

        this->GetWindowPlacement(&w); //윈도우의 정보를 저장한다. 

        CString strRect; 

        strRect.Format("%04d,%04d,%04d,%04d", //04d 는 4자리 확보하고 남은건 0으로 채워라 

                w.rcNormalPosition.left,w.rcNormalPosition.top, 

                w.rcNormalPosition.right,w.rcNormalPosition.bottom); //윈도우의 위치,크기 확보.. 

         

        BOOL bMax,bMin; //윈도우의 상태를 저장하기위한 변수 

        //w.falg 는 이전상태의 정보를 가지고 잇다!! 

        if(w.showCmd==SW_SHOWMINIMIZED)           //최소화 상태 

        { 

                bMin=TRUE; 

                if(w.flags==0) //falg 값이 0 이면 이전 상태가 보통상태이다!! 

                        bMax=FALSE; 

                else    //이전상태가 최대화 상태 

                        bMax=TRUE; 

        } 

        else                             

        { 

                if(w.showCmd==SW_SHOWMAXIMIZED) //최대화상태 

                { 

                        bMax=TRUE; 

                        bMin=FALSE; 

                } 

                else  //보통 상태 

                { 

                        bMax=FALSE; 

                        bMin=FALSE; 

                } 

        } 

        AfxGetApp()->WriteProfileString("WinStatus","Rect",strRect); 

        AfxGetApp()->WriteProfileInt("WinStatus","Max",bMax); 

        AfxGetApp()->WriteProfileInt("WinStatus","Min",bMin); 

 


//읽어올차례.. 

ActivateFrame 함수로 가서 

        WINDOWPLACEMENT w;  //윈도우의 상태를 저장하는 구조체.. 

        BOOL bMax,bMin;               //최대,최소상태를 저장할 변수 

        CString strRect; //창크기를 받아올 변수 

        strRect=AfxGetApp()->GetProfileString("WinStatus","Rect","0000,0000,0500,0700"); 

        bMin=AfxGetApp()->GetProfileInt("WinStatus","Min",FALSE); 

        bMax=AfxGetApp()->GetProfileInt("WinStatus","Max",FALSE); 

        int a=atoi(strRect.Left(4)); //문자열을 int 로 바꿔준다. 

        int b=atoi(strRect.Mid(5,4));     //atoi 아스키 값을 int형으로 바꿔준다.. 

        int c=atoi(strRect.Mid(10,4)); 

        int d=atoi(strRect.Mid(15,4)); 

        w.rcNormalPosition=CRect(a,b,c,d); 

        if(bMin) 

        { 

                w.showCmd=SW_SHOWMINIMIZED; 

                if(bMax) 

                { 

                        w.flags=WPF_RESTORETOMAXIMIZED  ; 

                } 

                else 

                { 

                        w.flags=0; 

                } 

        } 

        else 

        { 

                if(bMax) 

                { 

                        w.showCmd=SW_SHOWMAXIMIZED; 

                } 

                else 

                { 

                        w.showCmd=SW_SHOWNORMAL; 

                } 

        } 

        this->SetWindowPlacement(&w); //설정된 값으로 윈도우를 그리게 한다.. 

         

        //CFrameWnd::ActivateFrame(nCmdShow); //이건 반드시 주석처리한다.. 

 


40. progress Bar 쓰기 

 


        m_progress.SetRange(m_first,m_last); //Progress 범위설정하기 

        m_progress.SetStep(m_step); //Progress Step설정하기 

        //m_progress.StepIt(); //스텝만큼 움직이기 

        //또는 다음을 사용한다 

        for(int a=m_first;a<=m_last;a+=m_step) //a가 처음부터 끝까지 

        { 

                m_progress.SetPos(a); // 위치를 a에 맞춘다 

                Sleep(50); //천천히 움직이게한다 

        } 

 


41. 파일대화상자 FileDialog 사용하기 

void CConDlg1::OnFileopen()  //파일열기 버튼 

{ 

        CFileDialog *fdlg; //파일대화상자 객체 생성 // 포인터로 만든다.. 

        static char BASED_CODE szFilter[] = "Animate Video Files (*.avi)|*.avi|All Files (*.*)|*.*||"; 

        //필터를 만들어 준다..이건 할줄 모름.. 

        fdlg =new CFileDialog(TRUE, ".avi", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,szFilter); 

        //대화상자 만들기..이렇게 해야댄다.. 

        if(fdlg->DoModal()==IDOK) //이제..대화상자를 띠우고..     

        {                               //OK 누르면 실행될 부분.. 

                m_filename=fdlg->GetPathName();        //대화상자에서 경로를 받아서 저장. 

                UpdateData(FALSE);     

        } 

} 

선생님이 해준거 //파일 다이얼로그 만들기 

CFileDialog fdlg(TRUE,"avi",".avi",OFN_OEVRWRITEPROMPT,"Vidoe Files(*.avi)|*.avi|All Files(*.*)|*.*||"); 

 


42. Animate Control 사용하기 

        m_animate.Open(m_filename); //파일을 연다 

        m_animate.Play(0,-1,1);  //(처음프레임,마지막프레임,반복횟수) 

        m_animate.Stop(); //정지시키기 

        m_ani.SetAutoStart(TRUE); //자동으로 시작한다 

43. Control 의 Style 바꿔주기 

        Control.ModyfyStyle(제거할스타일,추가할스타일); //스타일은 MSDN내용 참조 

 


44. 시스템 날자바꾸기 버튼 

//SetSystemTime(),GetSystemTime() //GMT 표준시를 가져온다. 

//GetLocalTime(),SetLocalTime()  //현재 지역시간을 가져온다. 

 


        SYSTEMTIME st; 

        GetLocalTime(&st); //현재 시간, 날자를 넣는다. 

        st.wYear=m_date2.GetYear(); 

        st.wMonth=m_date2.GetMonth(); 

        st.wDay=m_date2.GetDay(); 

        SetSystemTime(&st); 

 


45. 시스템 시간 바꾸기 버튼 

        UpdateData(TRUE); 

        SYSTEMTIME st; 

        GetLocalTime(&st); 

        st.wHour=m_time.GetHour(); 

        st.wMinute=m_time.GetMinute(); 

        st.wSecond=m_time.GetSecond(); 

        SetLocalTime(&st); 

 


46.시스템의 드라이브 문자 얻기 

 


        char temp[50]; 

        GetLogicalDriveStrings(sizeof(temp),temp); 

        CString str,str1; 

        int n=0; 

        while(*(temp+n)!=NULL) 

        { 

                str=temp+n; 

                str1+= " "+str.Left(2); 

                n+=4; 

        } 

 


47. 현재 작업경로 얻기 

        char temp[MAX_PATH]; //MAX_PATH 는 경로길이의 최대를 define 해놓은것. 

        GetCurrentDirectory(sizeof(temp),temp);  // 현작업하는 경로를 얻어온다.(경로 길이,문자형); 

 


48. Tree Control 사용하기 

        HTREEITEM hmov,hmus; //핸들을받을 변수 이게 잇어야 하위 디렉토리 생성가능 

        hmov=m_tree.InsertItem("영화",TVI_ROOT,TVI_LAST); //,TVI_ROOT,TVI_LAST는 default 

        hm1=m_tree.InsertItem("외화",hmov);  //hmov 아래 “외화”트리 생성 

        CImageList m_image; //그림을 사용하기 위한 클래스다!! 알아두자.. 

        m_tree.SetImageList(&m_image,TVSIL_NORMAL); //Tree View Style Image List => TVSIL 

        hmov=m_tree.InsertItem("영화",0,1,TVI_ROOT,TVI_LAST); //,TVI_ROOT,TVI_LAST는 default 

        hmus=m_tree.InsertItem("가요",1,2); //("문자열",처음그림번호,선택시그림) 

        hm1=m_tree.InsertItem("외화",2,3,hmov); //그림 번호는 default 로 0이 들어간다.. 

 


49. List Control 사용하기 

        m_list.ModifyStyle(LVS_TYPEMASK, LVS_ICON); //리스트를 큰아이콘형태로 보인다 

        m_list.ModifyStyle(LVS_TYPEMASK, LVS_SMALLICON);  //리스트를 작은아이콘형태로 보인다 

        m_list.ModifyStyle(LVS_TYPEMASK, LVS_LIST); //리스트를 리스트형태로 보인다 

        m_list.ModifyStyle(LVS_TYPEMASK, LVS_REPORT); //리스트를 자세히형태로 보인다 

 


        CImageList m_treeimage; //이미지리스트 

        CImageList m_small, m_large; 

        m_large.Create(IDB_LARGE,32,0,RGB(255,255,255)); //이거는 클래스에서 추가해준거다 

        m_small.Create(IDB_SMALL,16,0,RGB(255,255,255)); (bmp ID값, 

        m_list.SetImageList(&m_large,LVSIL_NORMAL); 

        m_list.SetImageList(&m_small,LVSIL_SMALL); 

        CString name[]={"홍길동","진달래","한국남","개나리"}; 

        CString tel[]={"400-3759","304-7714","505-9058","700-9898"}; 

        CString born[]={"1980-1-1","1981-12-20","1980-05-15","1981-08-31"}; 

        CString sex[]={"남자","여자","남자","여자"}; 

         

        m_list.InsertColumn(0,"이름",LVCFMT_LEFT,70); 

        m_list.InsertColumn(1,"전화번호",LVCFMT_LEFT,80); 

        m_list.InsertColumn(2,"생일",LVCFMT_LEFT,90); 

        m_list.InsertColumn(3,"성별",LVCFMT_LEFT,50); 

        LVITEM it; //리스트 구조체 

        char temp[100]; 

        for(int a=0;a<4;a++) 

        {        

                int n=(sex[a]=="남자")?0:1; 

                m_list.InsertItem(a,name[a],n); //insert item 은 행을 만들고.. 

                it.mask=LVIF_TEXT|LVIF_IMAGE; //마스크 설정 

                it.iItem=a; 

                it.iSubItem=1; //열 설정 

                strcpy(temp,tel[a]); //이거 모하는거냐.. 

                it.pszText=temp; 

                m_list.SetItem(&it);                      // setitem 열에 정보를 넣는다. 

 


                it.iSubItem=2; //열 설정 

                strcpy(temp,born[a]); //이거 모하는거냐.. 

                it.pszText=temp; 

                m_list.SetItem(&it);                      // setitem 열에 정보를 넣는다. 

 


                it.iSubItem=3; //열 설정 

                strcpy(temp,sex[a]); //이거 모하는거냐.. 

                it.pszText=temp; 

                m_list.SetItem(&it);                      // setitem 열에 정보를 넣는다. 

 

 

 

50. Bitmap Button 사용하기 

  CBitmapButton 을 사용한다! CButton 에서 상속 받는클래스임.. 

        m_button1.Create(NULL, 

                WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,CRect(310,20,370,50), 

                this,IDC_MYBUTTON); //버튼만들기 

        m_button1.LoadBitmaps(IDB_UP,IDB_DOWN,IDB_FOCUS,IDB_DISABLE); //버튼의 그림설정 

        m_button1.SizeToContent(); //버튼을 그림 크기로 맞춰 준다!! 

 


 그냥 버튼을 비트맵버튼으로 바꾸기 -> 버튼을 만든다 속성에서 OWNERDRA 속성에 체크!! 

        m_button2.LoadBitmaps(IDB_UP,IDB_DOWN,IDB_FOCUS,IDB_DISABLE); //버튼의 그림설정 

        m_button2.SizeToContent(); //버튼을 그림 크기로 맞춰 준다!! 

 


51. 중복없는 난수발생하기 

        int su; //발생된 난수저장 

        int a,b; 

        BOOL bDasi; //숫자가중복될경우 다시하기위한 변수 

        for(a=0;a<9;a++)  //난수 9개 발생 

        { 

                bDasi=TRUE; 

                while(bDasi) 

                { 

                        bDasi=FALSE; 

                        su=rand()%10; //난수발생 

                        for(b=0;b 

                        { 

                                if(temp[b]==su)  //중복이면 

                                { 

                                        bDasi=TRUE; //중복이 잇으면 다시while 문을 실행한다 

                                        break; 

                                }//if 

                        }//for 

                }//while 

                temp[a]=su; //중복이 아니면 대입한다 

 


52. 메뉴 범위로 사용하기 

  ON_COMMAND_RANGE(ID_LEVEL3,ID_LEVEL9,OnLevel); //범위메세지 발생 

  //메뉴 ID의 값이 연속된 숫자일 경우 범위로 지정해서 사용할수잇다 

 


53. 한,영 전환함수 

void CCustView::SetHangul(BOOL bCheck) //T:한글 F:영문 이건 외우자.. 

{ 

        HIMC hm=ImmGetContext(this->GetSafeHwnd()); //뷰클래스의 윈도우 핸들포인터를 얻는다. 

        if(bCheck) 

        { 

                ::ImmSetConversionStatus(hm,1,0); //1은 한글 0은 영문 

        } 

        else 

        { 

                ::ImmSetConversionStatus(hm,0,0); //영문으로 바꿔준다 

        } 

        ::ImmReleaseContext(this->GetSafeHwnd(),hm); //장치를 풀어준다 

} 

#include "imm.h" //헤더 반드시 추가하고 

imm32.lib (라이브러리 파일)를 반드시 링크해주어야 한다! 

**** 라이브러리 추가하기 

프로젝트메뉴 -> 셋팅 -> 링크탭 

 


54. DLL함수정의하기 

임포트함수 :  extern "C"  __declspec(dllimport)   리터형  함수명(매개변수,...) ; 

  - 메인프로그램에서 DLL에 있는 함수를 호출할때 사용한다. 

 


엑스포트함수 :  extern "C"  __declspec(dllexport)   리터형  함수명(매개변수,...) 

                      { 

                             내용; 

                      } 

출처 : Tong - navy9370님의 MFC통 


'온라인게임 > vc++' 카테고리의 다른 글

숭실대학교 미디어대학원 컴퓨터그래픽스 Magic  (0) 2010.10.05
MFC 표기법  (0) 2010.10.05
컨트롤과 클래스 연결  (0) 2010.10.05
개별 개발자를 위한 도구  (0) 2010.10.03
vs 2010 설치  (0) 2010.10.03
 
u대화상자의 데이터 관리를 도와주는 함수임
u DDV(dialog Data Validation)
Ø 컨트롤과 변수에 연결된 데이터를 확인하는데 사용함
u DDX(dialog Data eXcahnge)
Ø 대화상자의 컨트롤에 데이터를 보내거나 받을때 사용함.

 컨트롤과 클래스의 연결방법- 1번째
DDX를 이용하는 방법
컨트롤과 연결되는 방법
Value :
»컨트롤과 변수를 연결하여 컨트롤에 입력된 값을 변수에 저장
»DDX_Text 계열 함수를 이용하여 자원에 연결


 Control :
»해당 컨트롤을 제어할 수 있는 컨트롤 클래스와 연결
»DDX_Control 계열 함수를 이용하여 자원에 연결





컨트롤과 Value형 멤버 변수 연결
 
다이얼로그 템플릿에서 Value형 멤버 변수와 연결시키려는 컨트롤을 선택à [Ctrl]키를 누른 상태에서 마우스 버튼을 더블 클릭


컨트롤과 Value형 멤버 변수 연결
 
n코드의 변화

DDX
관련 함수
DDX_Control : 리스트박스, 콤보박스등과
같은 컨트롤들에 대한 리소스를 해당 멤버변수에 연결함
DDX_Text : 에디터상자 컨트롤을 CString, int, long, UINT 형태의 멤버변수에 연결할때 사용함
.
DDX_Check : 체크상자 컨트롤을 int, BOOL 형태의 멤버변수에 연결할때 사용함
.
DDX_Radio : 라디오버튼 컨트롤을 해당 멤버 데이터에 연결할때
사용함

컨트롤과 클래스의 연결방법- 2번째

 —컨트롤의 핸들로 클래스와 연결하는 방법
핸들을 얻기 위해 컨트롤의 포인터를 받을 포인터 변수를 선언
GetDlgItem() 함수를 이용하여 컨트롤의 포인터를 선언된 포인터 변수에 치환한다.
클래스의 멤버를 이용하여 컨트롤을 다룬다.
)

CListBox *pList;

pList = (CListBox *)GeDlgItem(IDC_LIST1); 

pList->AddString(“데이터”);

'온라인게임 > vc++' 카테고리의 다른 글

MFC 표기법  (0) 2010.10.05
기능  (0) 2010.10.05
개별 개발자를 위한 도구  (0) 2010.10.03
vs 2010 설치  (0) 2010.10.03
C++ Beginner's Guide 3  (0) 2010.10.03
visual studio 2010

professional

MSDN

Visual Studio 2010 Professional(MSDN Essentials 포함)

작업 영역 사용자 지정

응용 프로그램 코드를 작성하다 보면 여러 디자이너와 편집기를 동시에 열어야 하는 경우가 종종 있습니다. Visual Studio 2010 Professional을 사용하면 멀티 모니터 지원 기능으로 디지털 환경을 구성 할 수 있으며, 이를 통해 작업 방식을 더 쉽게 관리할 수 있습니다.



SharePoint에서 공동 작업 솔루션 만들기

웹 파트, 목록, 워크플로, 이벤트 등에 대한 도구를 포함하는 새로운 SharePoint 개발 지원 기능을 사용하여 사용자 지정된 공동 작업 도구를 회사에서 구현할 수 있습니다.



Window7에서 응용 프로그램 빌드 / .Net Framework4

Visual Studio 2010 Professional에는 Windows 7 기술의 선봉에 있는 멀티 터치 "리본" UI 구성 요소를 비롯한 Window 7 개발용 기본 제공 도구가 포함되어 있습니다.


RIA 및 WPF 응용 프로그램을 손쉽게 만들기

개발자와 디자이너는 WPF(Windows Presentation Foundation)의 새로운 끌어서 놓기 데이터 바인딩과 Silverlight 디자이너를 사용하여 Windows의 RIA(Rich Internet Application)를 빠르고 쉽게 빌드할 수 있습니다.


웹 응용 프로그램 배포 간소화

클릭 한 번만으로 웹 응용 프로그램을 프로덕션 환경으로 이동할 수 있습니다.
Visual Studio 2010 Professional은 코드, IIS(Internet Information Server) 설정데이터베이스 스키마
대상 서버로 이전합니다.






통합 개발 환경

Visual Studio 2010 Professional은 다중 모니터를 지원하므로 작업을 원하는 대로 구성 및 관리할 수 있습니다.
또한 Windows 7을 비롯한 최신 플랫폼을 활용하는 비주얼 디자이너를 통해 창의력을 마음껏 발휘할 수 있습니다.


'온라인게임 > vc++' 카테고리의 다른 글

기능  (0) 2010.10.05
컨트롤과 클래스 연결  (0) 2010.10.05
vs 2010 설치  (0) 2010.10.03
C++ Beginner's Guide 3  (0) 2010.10.03
C++ Beginner's Guide 2  (0) 2010.10.03
visual studio 2010 ultimate 설치


Runtime / .Net Framework 4 / install 4.5 / F# 2.0 / Macro Tools / TFS 개체 모델


office 개발자 도구 / Dotfuscator / Crystal Reports / SQL Server Compact 3.5 / Sync FrameWork


ASP .NET MVC 2 /Silverlight 3


SQL Server 2008 / ADO .NET Entity Framework / Share Point /

'온라인게임 > vc++' 카테고리의 다른 글

컨트롤과 클래스 연결  (0) 2010.10.05
개별 개발자를 위한 도구  (0) 2010.10.03
C++ Beginner's Guide 3  (0) 2010.10.03
C++ Beginner's Guide 2  (0) 2010.10.03
표준 c++ / C++ 시작 1  (0) 2010.10.02

C++ Beginner's Guide 3

Table of Contents
CRITICAL SKILL 3.1: The if Statement ................................................................................................. 2

if(expression) {
statement sequence
}
else {
statement sequence
}

CRITICAL SKILL 3.2: The switch Statement ............................................................................................ 7
CRITICAL SKILL 3.3: The for Loop.................................................................................................... 13
CRITICAL SKILL 3.4: The while Loop ................................................................................................... 19
CRITICAL SKILL 3.5: The do-while Loop ............................................................................................... 21
CRITICAL SKILL 3.6: Using break to Exit a Loop ..................................................................................... 27
CRITICAL SKILL 3.7: Using continue .................................................................................................. 29

CRITICAL SKILL 3.8: Nested Loops ...................................................................................................... 34
CRITICAL SKILL 3.9: Using the goto Statement ................................................................................. 35



모든 강좌

Tier One: C++ Beginner's Guide

Essential skills made easy! Written by Herb Schildt,
this step-by-step book is ideal for first-time programmers or those new to C++.


The following downloads require
Adobe Reader:

'온라인게임 > vc++' 카테고리의 다른 글

개별 개발자를 위한 도구  (0) 2010.10.03
vs 2010 설치  (0) 2010.10.03
C++ Beginner's Guide 2  (0) 2010.10.03
표준 c++ / C++ 시작 1  (0) 2010.10.02
게임 서버  (0) 2010.10.02
C++ Beginner's Guide 2
C++ 초보 가이즈 2

Introducing Data Types and Operators
데이타 타입과 연산자 소개

Why Data Types Are Important
왜 데이타 타입들은 중요한가 ?

The data type of a variable is important 변수의 데이타 타입(종류)는 중요하다
because
it determines the operations  왜냐하면 그것은 조작을 결정하고
that
are allowed  그것은 허용되고
and the range of values that can be stored. 저장될수 있는 변수값의 범위 

C++ defines several types of data, and each type has unique characteristics.
c++ 몇가지 데이타 타입(종류)를 정의하고, 각 타입은 독특한 특징들을 가진다.

Because data types differ, all variables must be declared prior to their use,
때문에 데이타 타입 다르기, 모든 변수 해야하는 정의되어지는 이전에 그것들을 사용하기
and a variable declaration always includes a type specifier. 
그리고 변수 정의 항상 포함하다 타입 명시자
The compiler requires this information in order to generate correct code.
컴파일러 요구하다 이 정보 하기위해 생성하다 정확한 코드
In C++ there is no concept of a “type-less” variable.
에서 c++ 있지 않다 ~의 컨셉 타입없는 변수


CRITICAL SKILL 2.1: The C++ Data Types .......................................................................................... 2

At the core of the C++ type system are the seven basic data types shown here:
C++ 타입 시스템의 핵심에서 ---- 7개 기본 데이타 타입이 여기에 보여준다.

char         Character
wchar_t    Wide character
int          Integer
float        Floating point
double     Double floating point
bool        Boolean
void         Valueless

C++ allows certain of the basic types to have modifiers preceding them.
C++은 기본 타입들의 확신을 허용한다 --- 그것들의 앞에 수식자를 가질수 있다

signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to int.

Table 2-1 shows all valid combinations of the basic types and the modifiers.
테이블 2-1은  기본 타입과  수식자의 모든 유효한 조합을 보여준다.



Since C++ specifies only the minimum range a data type must support,
때문에 c++ 조건으로 말하다단지 최소 범위 데이타 타입을 지원해야 한다.
you should check your compiler’s documentation for the actual ranges supported.
체크해야한다 . 컴파일러의 문서 - 실제 범위 지원되는

For example, 예를들어
Table 2-2 shows typical bit widths and ranges for the C++ data types in a 32-bit environment,
테이블 2-2 전형적인 비트 폭과 범위 -위한 - c++ 데이타 타입 32비트 환경에서
such as that used by Windows XP. 
이를테면 윈도우xp를 사용하고 있을때

Let’s now take a closer look at each data type.

char 32bits = 2 x 2 x 2 x 2  x  2  x 2  x 2  x 2 = 8자리 = 2bytes
int 4bytes == long int
short int 2 bytes




float 6자리 / double 10자리 / long double 10자리


To understand the difference between the way that signed and unsigned integers are interpreted by C++,
하기위해 이해 차이점 사이 부호있는 부호없는 정수 c++에 의해 번역되는 방법
try this short program:
이 작은 프로그램을 해보라
 short int i;
 int j;
 j = 60000;
 i = j;
 cout << i << " " << j ;

short int는 -32768 ~ 32767사이인데 60000은 값의 범위를 벗어나다.

The seven basic types are char, wchar_t, int, float, double, bool, and void.


A signed integer can hold both positive and negative values.
An unsigned integer can hold only positive values.


Can a char variable be used like a little integer? Yes


The primary difference between float and double is in the magnitude(크기) of the values they can hold.

Project 2-1 Talking to Mars ............................................................................................................ 10
CRITICAL SKILL 2.2: Literals ............................................................................................................ 12
CRITICAL SKILL 2.3: A Closer Look at Variables .............................................................................. 15
CRITICAL SKILL 2.4: Arithmetic Operators ...................................................................................... 17
CRITICAL SKILL 2.5: Relational and Logical Operators ................................................................ 20
Project 2-2 Construct an XOR Logical Operation ........................................................................... 22
CRITICAL SKILL 2.6: The Assignment Operator ................................................................................. 25
CRITICAL SKILL 2.7: Compound Assignments .................................................................................... 25
CRITICAL SKILL 2.8: Type Conversion in Assignments ..................................................................... 26
CRITICAL SKILL 2.9: Type Conversion in Expressions ...................................................................... 27
CRITICAL SKILL 2.10: Casts.............................................................................................................. 27
CRITICAL SKILL 2.11: Spacing and Parentheses ................................................................................. 28
Project 2-3 Compute the Regular Payments on a Loan ................................................................. 29



모든 강좌

Tier One: C++ Beginner's Guide

Essential skills made easy! Written by Herb Schildt,
this step-by-step book is ideal for first-time programmers or those new to C++.


The following downloads require
Adobe Reader:

'온라인게임 > vc++' 카테고리의 다른 글

vs 2010 설치  (0) 2010.10.03
C++ Beginner's Guide 3  (0) 2010.10.03
표준 c++ / C++ 시작 1  (0) 2010.10.02
게임 서버  (0) 2010.10.02
vs 2010 (vc++ 10)  (0) 2010.10.01

Visual C++ 2008에서는 Visual Studio 개발 환경을 사용하여 표준 C++ 프로그램을 만들 수 있습니다
이 응용 프로그램은 ISO C++ 98 표준의 일부인 STL(표준 템플릿 라이브러리)에서 set 컨테이너를 사용합니다

Visual c++은
ISO C 95
ISO C++ 98
ECMA C++/CLI 05
의 표준을 따른다

이제 C++를 배우기 시작하는 초보자는
Herb Schildt가 쓴 "C++ Beginner's Guide"
(http://go.microsoft.com/fwlink/?LinkId=115303)를 참조하는 것이 좋습니다.

 

새 프로젝트를 만들고 소스 파일을 추가하려면

  1. 새 프로젝트를 만들려면

    파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트...를 클릭합니다.

  2. Visual C++ 프로젝트 형식에서 Win32를 클릭한 다음 Win32 콘솔 응용 프로그램을 클릭합니다.

  3. 프로젝트 이름을 입력합니다.

    프로젝트가 포함된 솔루션의 이름은 기본적으로 새 프로젝트의 이름과 동일하지만 사용자가 직접 다른 이름을 입력할 수도 있습니다. 원하는 경우 프로젝트의 위치를 다른 곳으로 지정할 수 있습니다.

    확인을 클릭하여 새 프로젝트를 만듭니다.

  4. Win32 응용 프로그램 마법사에서 빈 프로젝트를 선택하고 마침을 클릭합니다.

  5. 솔루션 탐색기가 열려 있지 않으면 보기 메뉴에서 솔루션 탐색기를 클릭합니다.

  6. 프로젝트에 새 소스 파일을 추가합니다.

    • 솔루션 탐색기에서 소스 파일 폴더를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목을 클릭합니다.

    • 코드 노드에서 C++ 파일 (.cpp)을 클릭하고 파일 이름을 입력한 다음 추가를 클릭합니다.

    .cpp 파일이 솔루션 탐색기의 소스 파일 폴더와 탭 창에 나타납니다. 이 창에서 필요한 코드를 입력할 수 있습니다.

  7. Visual Studio에서 새로 만들어진 탭을 클릭하고 표준 C++ 라이브러리를 사용하는 올바른 C++ 프로그램을 입력하거나 샘플 프로그램 중 하나를 복사하여 붙여넣습니다.

    예를 들어, 도움말의 STL 샘플 항목에 있는 set::find (STL Samples) 샘플 프로그램을 사용할 수 있습니다.

    이 절차에 샘플 프로그램을 사용하는 경우 using namespace std; 지시문에 주목할 필요가 있습니다. 이 지시문을 사용하면 프로그램에서 정규화된 이름(std::coutstd::endl) 대신 coutendl을 사용할 수 있습니다.

  8. 빌드 메뉴에서 솔루션 빌드를 클릭합니다.

    빌드 로그의 위치 및 빌드 상태를 나타내는 메시지 등의 컴파일 진행 상황 정보가 출력 창에 표시됩니다.

  9. 디버그 메뉴에서 디버깅하지 않고 시작을 클릭합니다.

    샘플 프로그램을 사용한 경우 집합에서 특정 정수를 찾았는지 표시하는 명령 창이 나타납니다.


 // set::find (STL Samples)
#include <set>
// Standard Template Library (STL) function in Visual C++.

#include <iostream>

using namespace std ;
// std::cout -> cout , std::endl->endl

typedef set<int> SET_INT;

void truefalse(int x)
{
 cout << (x?"True 참":"False 거짓") << endl;
}
//      Illustrates how to use the find function to get an iterator
//      that points to the first element in the controlled sequence
//      that has a particular sort key.
//
// Functions:
//
//    find         Returns an iterator that points to the first element
//                 in the controlled sequence that has the same sort key
//                 as the value passed to the find function. If no such
//                 element exists, the iterator equals end().

int main()
{
 SET_INT s1;

 cout << "s1.insert(5)" << endl;
 s1.insert(5);

 cout << "s1.insert(8)" << endl;
 s1.insert(8);

 cout << "s1.insert(12)" << endl;
 s1.insert(12);

 SET_INT::iterator it;

 cout << "it=find(8)" << endl;
 it = s1.find(8);

 cout << "it != s1.end() returned " ;
 truefalse( it != s1.end() ); // True

  cout << "it=find(6)" << endl;
 it = s1.find(6);

 cout << "it != s1.end() returned " ;
 truefalse( it != s1.end() ); // False
 cout << "";
}




Herb Schildt가 쓴 "C++ Beginner's Guide"


 C++ is derived from C.
Increasing program complexity was the main factor that drove the creation of C++.
C++ is the parent of Java and C#. True or False? 사실이다

method subroutine fuction
The term method was popularized by Java.
What a C++ programmer calls a function, a Java programmer calls a method.
C# programmers also use the term method

Encapsulation, polymorphism, and inheritance are the principles of OOP. (E P I )
The class is the basic unit of encapsulation in C++.
Function is the commonly used term for a subroutine in C++.


/* This is a simple C++ program.
Call this file Sample.cpp. */

This is a comment

#include <iostream>
The C++ language defines several headers,
which contain information that is either necessary
or useful to your program.

using namespace std;
This tells the compiler to use the std namespace.


int main()
All C++ programs are composed of one or more functions

cout << "C++ is power programming.";
This is a console output statement.

return 0;
This line terminates main( ) and causes it to return the value 0
to the calling process (which is typically the operating system)


A C++ program begins execution with main( ).
cout is a predefined identifier that is linked to console output.
It includes the header <iostream>, which supports I/O.

변수 : 정의 할당 출력

연산자
+ Addition
- Subtraction
* Multiplation
/ Division


C++ variables must be declared before they are used.

cout << "Enter the length: ";
cin >> length; // input the length

The input operator is >>.
cin is linked to the keyboard by default
The \n stands for the newline character.

The integer data type is int.
double is the keyword for the double floating-point data type.


conditional expression

Operator Meaning

<
Less than
<=
Less than or equal
>
Greater than
>=
Greater than or equal
==
Equal to
!=
Not equal


if is C++’s conditional statement
The for is one of C++’s loop statements
The relational operators are ==, !=, <, >, <=, and >=.


Blocks

if(w < h) {
    v = w * h;
    w = 0;
}
Here, if w is less than h, then both statements inside the block will be executed

A block is started by a {. It is ended by a }. A block creates a logical unit of code.

In C++, statements are terminated by a ____________. semicolon ;

A function is a subroutine that contains one or more C++ statements.

The C++ standard function library is a collection of functions supplied by all C++ compilers

c++ 키워드 63
There are 63 keywords currently defined for Standard C++



In C++, all keywords are in lowercase. for For FOR
A C++ identifier can contain letters, digits, and the underscore.
C++ is case sensitive. index21 Index21

[문제]

1. It has been said that C++ sits at the center of the modern programming universe. Explain this
statement.
2. A C++ compiler produces object code that is directly executed by the computer. True or false?
3. What are the three main principles of object-oriented programming?
4. Where do C++ programs begin execution?
5. What is a header?
6. What is <iostream>? What does the following code do?
    #include <iostream>
7. What is a namespace?
8. What is a variable?
9. Which of the following variable names is/are invalid?

  a. count
  b. _count
  c. count27
  d. 67count
  e. if
10. How do you create a single-line comment? How do you create a multiline comment?
11. Show the general form of the if statement. Show the general form of the for loop.
12. How do you create a block of code?
13. The moon’s gravity is about 17 percent that of Earth’s. Write a program that displays a table that shows Earth   pounds and their equivalent moon weight. Have the table run from 1 to 100 pounds. Output a newline every 25 pounds.
14. A year on Jupiter (the time it takes for Jupiter to make one full circuit around the Sun) takes about 12 Earth years.   Write a program that converts Jovian years to Earth years. Have the user specify the number of Jovian years. Allow   fractional years.
15. When a function is called, what happens to program control?
16. Write a program that averages the absolute value of five values entered by the user. Display the result.


모든 강좌

Tier One: C++ Beginner's Guide

Essential skills made easy! Written by Herb Schildt,
this step-by-step book is ideal for first-time programmers or those new to C++.


The following downloads require
Adobe Reader:

  • Download all 12 chapters, answers and appendix
  • Chapter 1 Fundamentals
  • Chapter 2 Introducing Data Types and Operators
  • Chapter 3  Porgram Control Statements
  • Chapter 4 Arrays, Strings, Pointers 배열 , 문자열, 포인터
  • Chapter 5 Introducing Functions
  • Chapter 6 Closer Look at Functions
  • Chapter 7 More Data Types and Operators
  • Chapter 8 Classes and Objects
  • Chapter 9 A Closer Look at Classes
  • Chapter 10 Inheritance,Virtual Functions and Polymorphism
  • Chapter 11 The C++ I/O System
  • Chapter 12 Exceptions, Templates, and Other Advanced Topics
  • Answer Key Answers to Mastery Checks
  • Appendix A The Prepocessor


    [저자소개]
    Herbert Schildt 허버트 쉴드
    아주 저명한 프로그래밍 서적 저술가이다. 그는 C, C++, 자바 언어의 권위자이며, 윈도우 프로그래밍의 대가로 알려져 있다. 그가 집필한 프로그래밍 서적은 전 세계적으로 300만 부 이상 팔려왔으며, 거의 모든 주요 언어로 번역 출판되었다. 그는 [Java 2 : The Complete Reference], [Java 2: A Beginner?s Guide], [Java 2 Programmer?s Reference], [C++ : The Complete Reference], [C : The Complete Reference], 그리고 [C# : The Complete Reference]를 포함한 다수의 베스트셀러 저자이다. 

'온라인게임 > vc++' 카테고리의 다른 글

C++ Beginner's Guide 3  (0) 2010.10.03
C++ Beginner's Guide 2  (0) 2010.10.03
게임 서버  (0) 2010.10.02
vs 2010 (vc++ 10)  (0) 2010.10.01
온라인 게임 서버  (0) 2010.10.01

+ Recent posts