로그인

검색

API/MFC
2013.07.28 02:24

MFC TIP

MoA
조회 수 1027 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄

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 ViewSetCursor 사용

   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. 4Class간참조

 //각각헤더파일include

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

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

 #include "ClassView.h" //Viewinclude 할때는반드시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 toolbarn");

                 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. ToolBarComboBox붙이기

         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 값이이면이전상태가보통상태이다!!

                        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_LASTdefault

        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_LASTdefault

        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)   리터형 함수명(매개변수,...)

                       {

                              내용;

                       }

 

1차 출처 : Tong - navy9370님의MFC

2차 출처 : http://loginpark.net/120092819905

[출처] MFC TIP|작성자 나우누리

?

  1. Programming 게시판 관련

    Date2014.11.01 CategoryTool/etc ByMoA Views5726
    read more
  2. #pragma

    Date2013.07.28 CategoryAPI/MFC ByMoA Views888
    Read More
  3. DirectX 9.0c SDK을 Visual Studio2008에 적용방법

    Date2013.07.28 CategoryGraphic ByMoA Views758
    Read More
  4. Video Preview and Frames Capture

    Date2013.07.28 CategoryGraphic ByMoA Views1797
    Read More
  5. MFC TIP

    Date2013.07.28 CategoryAPI/MFC ByMoA Views1027
    Read More
  6. 이미지공학(IE) 연구실

    Date2013.07.28 CategorySite ByMoA Views686
    Read More
  7. CString class

    Date2013.07.28 CategoryAPI/MFC ByMoA Views1167
    Read More
  8. Visual C++ 시리얼 통신(RS-232) 강좌 (2)

    Date2013.07.28 CategoryAPI/MFC ByMoA Views5456
    Read More
  9. Visual C++ 시리얼 통신(RS-232) 강좌 (1)

    Date2013.07.28 CategoryAPI/MFC ByMoA Views7408
    Read More
  10. High-speed Charting Control

    Date2013.07.28 CategoryLibrary ByMoA Views1107
    Read More
  11. DLL 이란

    Date2013.07.28 CategoryAPI/MFC ByMoA Views1470
    Read More
  12. extern "C" 에 관하여

    Date2013.07.28 CategoryC/C++ ByMoA Views1303
    Read More
  13. UpdateData(TRUE) or UpdateData(FALSE) 구분

    Date2013.07.28 CategoryAPI/MFC ByMoA Views1080
    Read More
  14. InvalidateRect 함수, flag성 메세지

    Date2013.07.25 CategoryAPI/MFC ByMoA Views998
    Read More
  15. UpdateWindow 함수에 대하여..

    Date2013.07.25 CategoryAPI/MFC ByMoA Views1080
    Read More
  16. 다이얼로그 resize 시 child control의 그래픽 깨짐 해결

    Date2013.07.25 CategoryAPI/MFC ByMoA Views1982
    Read More
  17. Property Sheet의 버튼 속성 변경하기

    Date2013.07.25 CategoryAPI/MFC ByMoA Views1407
    Read More
  18. CPaneDialog 초기화 (OnInitDialog)

    Date2013.07.18 CategoryAPI/MFC ByMoA Views2001
    Read More
  19. CDockablePane 버튼 비활성화 문제

    Date2013.07.17 CategoryAPI/MFC ByMoA Views2171
    Read More
  20. CDockablePane 배경화면 회색으로 변경

    Date2013.07.11 CategoryAPI/MFC ByMoA Views1621
    Read More
  21. What to use instead of “addPreferencesFromResource” in a PreferenceActivity?

    Date2013.06.13 CategoryJAVA/Android ByMoA Views1242
    Read More
Board Pagination Prev 1 ... 6 7 8 9 10 11 12 13 14 15 Next
/ 15