'분류 전체보기'에 해당되는 글 24건

  1. 2008.10.09 멀티 쓰레딩 by system 1
  2. 2008.01.31 삼성전자 새마을금고 특판 by system
  3. 2007.12.20 XP 스타일 버튼 만들기 by system 1
  4. 2007.12.19 GPS 데이터 구글맵 연동 by system
  5. 2007.12.18 CBitmapButton 커서 변경 by system
  6. 2007.12.11 SDI 기반에 Dialog 만들어 ScrollView 붙이기 by system 1
  7. 2007.12.10 Dialog에 View 붙이기 by system
  8. 2007.12.08 Window 깜빡임의 실체 - WM_ERASEBKGND와 WM_PAINT by system 3
  9. 2007.12.05 Data Type Conversion by system
  10. 2007.12.02 CHtmlView 깜빡임 제거하기 by system

multithread programming(1)

 

MFC에서의 Multithread

 

OS는 구분하지 않지만 MFC는 사용자 편의를 위하여 두 가지 형태로 지원

 

1.     Worker thread

2.     User Interface thread

 

Worker thread

 

::AfxBeginThread() 함수를 이용

 

CWinThread* ::AfxBeginThread(

       AFX_THREADPROC pfnThreadProc,

       LPVOID pParam,

       int nPriority = THREAD_PRIORITY_NORMAL, // 기본적으로 Process 동일

       UINT nStackSize = 0,

       DWORD dwCreateFlags = 0,                      // 0 또는 CREATE_SUSPENDED

       LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL

);

 

우선 Thread를 이용할 함수를 먼저 정의한다

 

UINT ThreadFunc(LPVOID pParam)

{

       int option = (int)pParam;

      

}

 

만약 인자가 많은 경우에는

 

typedef struct tagPARAMS

{

       ...

} PARAMS;

 

와 같이 한 후에

 

PARAMS *pParams = new PARAMS;

CWinThread *pThread = ::AfxBeginThread(ThreadFunc, &pParams);

 

와 같이 하고

 

UINT ThreadFunc(LPVOID pParam)

{

       PARAMS *pThreadParams = (PARAMS *)pParam;

       ...

       delete pThreadParams;

 

       return 0;

}

 

와 같이 사용하면 된다.

 

Thread를 잠시 중지시키고 싶을 때는 주 Process에서

 

pThread->SuspendThread();

 

다시 돌리고 싶을 때는 주 Process에서

 

pThread->ResumeThread();

 

와 같이 하면 된다.(Thread 자신이 호출할 수는 없다.)

또는 경우에 따라서는

 

Sleep(2000);

 

과 같이 사용할 수도 있는데 이 경우는 제어권을 다른 Process에 넘겨 주게 된다.

 

Sleep(0);

 

와 같이 할 경우에는 우선 순위가 높거나 같은 Process에 넘겨 주고 우선 순위가 높거나

같은 Process가 없을 경우에는 아무 일도 생기지 않는다.

 

Thread를 종료시키고 싶을 때는 TerminateThread() 함수를 사용하면 되는데 이 경우 Thread 함수가

내부 정리를 하지 못할 수가 있기 때문에 다음과 같은 방법이 많이 사용된다.

 

static BOOL bContinue = TRUE;

CWinThread *pThread = ::AfxBeginThread(ThreadFunc, &bContinue);

 

UINT ThreadPrintNum(LPVOID pParam)

{

       BOOL *pbContinue = (BOOL *)pParam;

       while ( *pbContinue )

       {

            

       }

       return 0;

}

 

와 같이 하고 bContinue 값을 FALSE로 하면 Thread 함수가 종료된다.

 

Thread가 완전히 종료된 것을 확신해야 하는 경우에는

 

if ( ::WaitForSingleObject(pThread->m_hThread, INFINITE) )

{

       // 이곳은쓰레드가확실히종료된상태임

}

 

와 같이 하면 된다. Thread가 죽어 버려서 먹통이 되는 경우까지 대비하려면

 

DWORD result;

result = ::WaitForSingleObject(pThread->m_hThread, 1000);   // 1초기다림

if ( result == WAIT_OBJECT_0 )

{

       // 이곳은쓰레드가확실히종료된상태임

}

else if ( result == WAIT_TIMEOUT )

{

       // 1초가지나도쓰레드가종료되지않은상태

}

 

이 방법을 사용해야 한다. 어떤 Thread가 현재 실행 중인지 알고 싶을 때는

 

if ( ::WaitForSingleObject(pThread->m_hThread, 0 ) == WAIT_TIMEOUT )

{

       // pThread 실행중

}

else

{

       // pThread가실행중이아님

}

 

와 같이 하면 된다.

 

User Interface Thread

 

User interface thread는 그 자체로 윈도우와 메시지 루프를 가지고 있다.

 

class CUIThread : public CWinThread

{

       DECLARE_DYNCREATE(CUIThread)

 

public:

       virtual BOOL InitInstance();

};

 

User interface thread 독자의 윈도우도 가질 있다. 일반적으로 전용 Dialog 띄워

Thread 처리하는 경우가 많으므로 User Dialog CMyDialog라고 이름 지었다고 가정하면

 

IMPLEMENT_DYNCREATE(CUIThread, CWinThread)

 

BOOL CUIThread::InitInstance()

{

       m_pMainWnd = new CMyDialog;

       m_pMainWnd->ShowWindow(SW_SHOW);

       m_pMainWnd->UpdateWindow();

       return TRUE;

}

 

와 같이 CMyDialog Thread로 띄울 수 있다. 그 다음

 

CWinThread *pThread = ::AfxBeginThread(RUNTIME_CLASS(CUIThread));

 

와 같이 하면 MFC가 알아서 CUIThread를 생성해서 그 포인터를 pThread에 넘겨 준다.

 

아래 예제에는 CMyDialog를 띄우고 주 Process는 사용자의

입력을 기다린다. Dialog Design 및 생성은 별도로 이야기하지 않는다. 아래 예제를 사용하기 위해서는

CMyDialog를 만들고 ID IDD_MYDIALOG라고 가정하면 CMyDialog의 생성자에 다음과 같이 추가해야 제대로 동작한다.

 

CMyDialog::CMyDialog(CWnd* pParent /*=NULL*/)

       : CDialog(CMyDialog::IDD, pParent)

{

       Create(IDD_MYDIALOG, NULL);

}

 

이제 완전히 별도로 동작하는(Thread로 동작하는) 윈도우를 하나 가지는 것이다. 만약 이것을 Dialog가 아닌

FrameWnd라고 해도 거의 똑같다. 다만 위에서도 언급했듯이 Thread를 이용할 때는 Dialog가 더 일반적일 것이다.

Worker thread에 비해 훨씬 더 많은 기능을 하는 것을 알게 되었을 것이다.

 

나머지 것들은 위의 Worker Thread에 있는 내용과 동일하다.

 

만약 여러 개의 CUIThread 를 여러 개 만들려고 한다면

 

CWinThread *pThread[5];

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

       m_pThread[i] = ::AfxBeginThread(RUNTIME_CLASS(CUIThread));

 

와 같이 하면 5개의 Thread가 생성된다.

 

Program Execution Priority(프로그램 실행 우선순위)

 

Thread 0~31까지의 priority를 가질 수 있다.

 

프로그램의 priority

 

BOOL SetPriorityClass(HANDLE hProcess, DWORD dwPriorityClass);

 

함수를 이용해서 조정할 수 있다. 첫 번째 인자 hProcess ::AfxGetInstanceHandle()로 얻으면 된다.

 

dwPriorityClass

Execution Priority

Description

IDLE_PRIORITY_CLASS

CPU IDLE일 때만 사용 가능

NORMAL_PRIORITY_CLASS

보통

HIGH_PRIORITY_CLASS

높은 우선 순위

REALTIME_PRIORITY_CLASS

최상위의 우선순위

 

Thread Execution Priority(쓰레드 실행 우선순위)

 

::AfxBeginThread() 함수의 nPriority를 통해서 설정하거나 CWinThread::SetThreadPriority 를 사용해 설정할 수 있다.

 

BOOL SetThreadPriority(HANDLE hThread, int nPriority);

 

nPriority

Execution Priority

Description

THREAD_PRIORITY_IDLE

REALTIME_PRIORITY_CLASS의 경우 16, 그 외에는 1

THREAD_PRIORITY_LOWEST

프로세스의 우선순위보다 2단계 낮은 우선순위를 가진다

THREAD_PRIORITY_BELOW_NORMAL

프로세스의 우선순위보다 1단계 낮은 우선순위를 가진다

THREAD_PRIORITY_NORMAL

프로세스의 우선순위가 같은 우선순위

THREAD_PRIORITY_ABOVE_NORMAL

프로세스의 우선순위보다 1단계 높은 우선순위를 가진다

THREAD_PRIORITY_HIGHEST

프로세스의 우선순위보다 2단계 높은 우선순위를 가진다

THREAD_PRIORITY_CRITICAL

REALTIME_PRIORITY_CLAS의 경우 31 그 외에는 16

 

프로그래머가 우선순위를 조정해도 Windows Scheduler가 상황에 맞게 조정하기 때문에 우선순위는

생각하고 조금 다를 수 있다.

 

Thread & Memory

 

Thread의 지역 변수는 모두 별도로 Stack을 만들고 Local Variable들을 관리하기 때문에 위의

 

CWinThread *pThread[5];

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

       m_pThread[i] = ::AfxBeginThread(RUNTIME_CLASS(CUIThread));

 

와 같은 경우에도 각 Thread가 다른 Thread를 침범하는 일은 없다.

 

이 쯤에서 끝났나 싶겠지만아직 갈 길이 멀다.

Critical section, Mutex, Semaphore 같은 것들은 다음에

 

Multithreading synchronization(멀티쓰레드의 동기화) => http://blog.naver.com/xtelite/50023359879

 

프로그램

 

Worker thread

 

#include "stdafx.h"

#include "console.h"

 

#include <iostream>

 

using namespace std;

 

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

 

// The one and only application object

CWinApp theApp;

 

using namespace std;

 

UINT ThreadPrintNum(LPVOID pParam);

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

       int nRetCode = 0;

 

       // initialize MFC and print and error on failure

       if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))

       {

             _tprintf(_T("Fatal Error: MFC initialization failed\n"));

             return 1;

       }

 

       static BOOL bContinue = TRUE;

       CWinThread *pThread = ::AfxBeginThread(ThreadPrintNum, &bContinue);

 

       int count = 0;

       while ( count < 1000 )

       {

             count++;

       }

 

       Sleep(1000);

       pThread->SuspendThread();

       cout << "Thread suspended. Waiting for 2 seconds" << endl;

 

       Sleep(2000);

       cout << "Thread resumed" << endl;

       pThread->ResumeThread();

 

       cout << "Quit thread" << endl;

       bContinue = FALSE;

       Sleep(100);

 

       return nRetCode;

}

 

// 쓰레드함수

UINT ThreadPrintNum(LPVOID pParam)

{

       BOOL *pbContinue = (BOOL *)pParam;

       int count = 0;

       while ( *pbContinue )

       {

             count++;

       }

       cout << "Exit thread" << endl;

       return 0;

}

 

User interface thread

 

#include "stdafx.h"

#include "console.h"

 

#include "MyDialog.h"

 

#include <cstdlib>

 

using namespace std;

 

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

 

// The one and only application object

CWinApp theApp;

 

using namespace std;

 

class CUIThread : public CWinThread

{

       DECLARE_DYNCREATE(CUIThread)

 

public:

       virtual BOOL InitInstance();

};

 

IMPLEMENT_DYNCREATE(CUIThread, CWinThread)

 

BOOL CUIThread::InitInstance()

{

       m_pMainWnd = new CMyDialog;

       m_pMainWnd->ShowWindow(SW_SHOW);

       m_pMainWnd->UpdateWindow();

       return TRUE;

}

 

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

       int nRetCode = 0;

 

       // initialize MFC and print and error on failure

       if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))

       {

             _tprintf(_T("Fatal Error: MFC initialization failed\n"));

             return 1;

       }

 

       CWinThread *pThread = ::AfxBeginThread(RUNTIME_CLASS(CUIThread));

      

       system("pause");

 

       return nRetCode;

}


Posted by system
l
새마을금고 정기 예/적금 재테크

2008/01/11 15:42

http://blog.naver.com/im5300sky/80046953323

안녕하십니까? 삼성전자새마을금고 수원지점 지점장을 맡고 있는 김 용훈 부장입니다.


희망찬 새해를 맞이하여 회원님의 가정에 건강과 행복이 가득하시기를 기원합니다.

보내주신 사랑과 성원에 힘입어 복지금융조합인 삼성전자새마을금고가 창립 30주년을 맞이했습니다.

1978년 자본금 1,000만원으로 시작하여 '07년에는 자산 1조원달성과 부실채권비율이 금융기관 중

가장 낮은 수준을 달성하여 양적으로나 질적으로 명실상부한 최고의 복지금융기관이 되었습니다.

이에 보답코자 아래와 같이 고금리 특판예금을 준비하였사오니 재산증식에 좋은 기회가 되셨으면

합니다.

(첨부: 특판행사 안내장, 지점안내, 이사장 신년사)

--------------------------------- 아  래 -------------------------------------------------

 

■ 행사기간: 2008. 1. 7 ~ 2. 29(한도 소진시 조기종료됨)

■ 인당한도: 제한 없음

구  분

1년

2년

3년

정기예탁금/정기적금

연 7.2%

연 7.4%

연 7.7%

 

■ 특판예금을 알차고 톡톡하게 이용하는 방법..!!

○ 이자소득에 대한 세금을 최대한 줄여 절세혜택을 노려라..!!

   목돈 1억원을 연7.2% 같은 금리로 맡겨도 세금에 따라 이자를 100만원 더 받는다

   - 비 과 세 : 생계형저축(가입자격: 노인(남 60세, 여55세 이상), 장애인, 국가유공자 등)) 1인당 3,000만원

   - 세금우대 : 조합금융(새마을금고 등) 거래 고객은 1인당 2,000만원까지 예금액의 이자소득세 면제

   - 세금우대종합 : 세금우대와 혼돈하면 안됨, 추가로 1인당 2,000만원까지 세금 약 6% 감면(9.5% 부과함)

   - 과    세 : 과세를 가입하시는 당신..! 행복한 사람.. 이자소득에 대하여 15.4% 세금부과    

... 비과세와 세금우대가 좋기는 한데...1인당 한도가 작다.... 애게.?...라고 생각하신다면..

○ 가족명의 예금으로 분산하여 세금혜택을 극대화 하라..!!

   삼성전자새마을금고는 직계가족(조부모,부모,배우자,성년자녀)의 예금가입이 가능합니다.

   ① K부서의 김과장은 부모님(부:60세, 모:55세)과 여우 같은 아내가 있고 덤으로 1억이 있다

      특판예금에 잘 운용할 수 있을까요..? (기간 1년, 금리 연 7.7% 가정시)

김과장 명의만 이용한다

배우자 명의도 이용한다

부모님 명의까지 이용한다

 세금우대 2,000만원(김과장)

 세금종합 2,000만원(김과장)

 과    세 6,000만원(김과장)

 --------------------

 세전이자  770만원

 세    금   88만원

 실제이자  682만원

 세금우대 4,000만원(김과장,배우자)

 세금종합 4,000만원(김과장,배우자)

 과    세 2,000만원(김과장)      

 --------------------

 세전이자  770만원

 세    금   57만원

 실제이자  713만원

 비 과 세 6,000만원(부모님)      

 세금우대 4,000만원(김과장,배우자)

 

 --------------------

 세전이자  770만원

 세    금    4만원

 실제이자  766만원

...... 그렇다면 특판예금은 어디서 가입하며 가족명의 예금은 어떻게 가입하나요..??

○ 행사기간 중 인터넷으로 해당상품에 가입하시면 특판금리가 자동 적용됩니다.

○ 다만, 가족명의 예금은 인터넷가입이 불가하며 창구에서 가입하셔야 합니다.

   - 본인명의 예금 : 인터넷으로 가입하셔야 특판금리를 100% 적용받으실 수 있습니다

   - 가족명의 예금 : 가족관계확인서류, 도장, 대리인의 신분증(가족회원것이 아님)을 지참하시고 창구에

                     방문하시어 가입합니다.

                     -> 가족회원이 인터넷거래를 원하실 경우 직접 내방해야 합니다

 ..... 추가로 궁금하신 사항은...아래 영업점으로 전화 주십시오...!!

 

☏ 디지털(R4)지점: 277-8241~3    정보통신(R3): 279-1705,7   한가족영업점  : 200-1347,8

   생활가전영업점: 200-1334      CS아카데미  : 270-2098     서울본관영업점: 02-728-4825,8

Posted by system
l
XP 스타일 버튼을 만드는 간단한 팁을 하나 소개해 드립니다.
VC++ 6.0 에서 프로그래밍을 하면 Windows XP 환경에서 프로젝트를 만들더라도
그림 (a) 처럼 버튼이밋밋한게 영 심심하지요. 그래서 10초만에 간단하게 그림 (b) 처럼
만들어주는 방법을 소개합니다.


  Step 1: 첨부한 xpstyle.xml 파일을 Resource Editor 에서 Import 하여 추가합니다.
  Step 2: Resource Type 은 숫자로 24 를 입력합니다.
  Step 3: IDR_241 이라는 항목 이름을 숫자 1 로 변경합니다.
  Step 4: 재컴파일 합니다.


    (a) 적용전                    (b) 적용후
 
사용자 삽입 이미지
Posted by system
l
@Sonygps/ver1.0/wgs-84
$GPGGA,021207,3726.0890,N,12708.0822,E,1,04,04.9,-00028.2,M,018.6,M,,*62
$GPGSA,A,3,11,17,20,28,,,,,,,,,14.3,04.9,13.4*01
$GPGSV,3,1,09,01,02,068,00,04,19,244,38,08,09,211,31,09,00,326,00*75
$GPGSV,3,2,09,11,43,054,45,17,43,309,44,19,04,099,00,20,56,113,42*75
$GPGSV,3,3,09,28,72,234,41,,,,,,,,,,,,*4F
$GPRMC,021207,A,3726.0890,N,12708.0822,E,001.4,000.0,140207,,,A*76
$GPVTG,000.0,T,,M,001.4,N,002.6,K,A*0C

이런 형식이 반복되어 저장되 있었다..
검색해보니.. NMEA-0183 Format 이었군..

021207 : 02시 12분 07초 (한국에서는 9를 더해야 한다.)
A : A = Valid, V = Invalid
3726.0890 : 위도 ddmm.mmmm
12708.0822 : 경도 dddmm.mmmm
140207 : 07년 02월 14일

소니의 이미지 트랙커만으로는 부족해서..
구글맵과 연동 해보기로 했다..

좌표가 구글과는 좀 달라서 애먹었는데..
앞자리 dd 인 부분은 그데로 쓰고..
뒤의 mm.mmmm 은 60 으로 나눠 앞자리와 더하면 된다..
ㅡ.ㅡ;;

그래서 구글맵에 적용 완료..

 
Posted by system
l

1. 버튼 생성

m_btnLowUnit[i] = new CBitmapButton;
m_btnLowUnit[i]->Create( NULL, WS_CHILD|WS_VISIBLE|BS_OWNERDRAW, *m_prtUnitLowRect[i], this, (UM_CLASS_SELECT+i+101) );


2. 이미지 삽입

m_btnLowUnit[6]->LoadBitmaps(IDB_STARTMENU_UP, IDB_STARTMENU_DN);  


3. 해당 동일 타입 버튼 위에 마우스 커서 이동 시, 손모양 커서 변경 설정
SetClassLong(m_btnLowUnit[6]->m_hWnd, GCL_HCURSOR, (long)AfxGetApp()->LoadCursor(IDC_HAND_CURSOR));

출처 : http://blog.naver.com/tazamara?Redirect=Log&logNo=130022814349

Posted by system
l

/**********************[다이알로그에다가 View 를 붙이자~~~~ ]***********************/


보통 작업할떄 다이알로그베이스로 많이 합니다. 간단하고 쉬어서 그럴껀데 그런데

이미지를 다룰려면 너무 복잡해집니다.. view처럼 아무곳에서ClientDC를 불러올수고 없고

그래서 요즘 제가 쓰는 방법이 다이알로그에 View를 붙이는 겁니다. 그럼면 정말 강력한 기능들을

쓸 수가 있습니다..

그럼 간략히 적어보면

우선 view클래스와 Document클래스 만듭니다..

다이알로그의 헤더에

 CFrameWnd m_Frame;
 CCreateContext pContex;
 CMyView *pView;<-뷰클래스
를 선언하고

다이알로그의 초기화 함수에서

  /* 뷰를 만드는 코드 */    
     CWnd* pFrameWnd = this;
     pContext.m_pCurrentDoc = new CMyDocument;<-도큐먼트클래스,
     pContext.m_pNewViewClass = RUNTIME_CLASS(CMyView);
     pView =(CMyView *) ((CFrameWnd*)pFrameWnd)->CreateView(&pContext);
     ASSERT(pView);
     pView->ShowWindow(SW_NORMAL);
                 pView->MoveWindows("원하는위치");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
아참 그리고
뷰클래스의 헤더 부분을 요로게 하세요...
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class CMyDlg;<-붙일 다이알로그
class CMyView : public CView
{
 DECLARE_DYNCREATE(CMyView)
    friend class CMyDlg;<-선언
protected:
    CMyView();           // protected constructor used by dynamic creation
    virtual ~CMyView();
 
public:
    #ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

protected:
    DECLARE_MESSAGE_MAP()
public:
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**************************************************************************************/



그냥 SDI 프로젝트에서 버튼을 누르면 뷰가 붙은 다이얼로그 창이 뜨게 만들었구요..


잘 동작하는거 같은데.. 다이얼로그에 붙은 뷰를 클릭하면 assertion failed이 남니다..


디버그를 해보면


int CView::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message){

    int nResult = CWnd::OnMouseActivate(pDesktopWnd, nHitTest, message);

    if (nResult == MA_NOACTIVATE || nResult == MA_NOACTIVATEANDEAT)

        return nResult;   // frame does not want to activate


    CFrameWnd* pParentFrame = GetParentFrame();

    if (pParentFrame != NULL)

    {

        // eat it if this will cause activation

        ASSERT(pParentFrame == pDesktopWnd || pDesktopWnd->IsChild(pParentFrame)); --> 이부분에서 에러가.. 납니다.


        // either re-activate the current view, or set this view to be active

        CView* pView = pParentFrame->GetActiveView();

        HWND hWndFocus = ::GetFocus();

        if (pView == this &&

            m_hWnd != hWndFocus && !::IsChild(m_hWnd, hWndFocus))

        {

            // re-activate this view

            OnActivateView(TRUE, this, this);

        }

        else

        {

            // activate this view

            pParentFrame->SetActiveView(this);

        }

    }

    return nResult;

}


혹시 무슨문제인줄 아시면 좀 가르쳐주세요.. ^^;; 죄송합니다..
====================================================================================
답변
====================================================================================

이름은 생각이 안나나.. 질문답변에 올라와있는 글을 보고 해결하였습니다.


답을 올려주신분이 WM_MOUSEACTIVATE를 추가하라고 하셨는데..


class wizard에 WM_MOUSEACTIVATE라는 메세지가 없드라구요..


그래서 MyView.cpp에


BEGIN_MESSAGE_MAP(CMyView, CView)

    //{{AFX_MSG_MAP(CMyView)

    ON_WM_MOUSEACTIVATE()

    //}}AFX_MSG_MAP

END_MESSAGE_MAP()



int CMyView::OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message)

{

    // TODO: Add your message handler code here and/or call default

   

//    return CView::OnMouseActivate(pDesktopWnd, nHitTest, message);

    return MA_ACTIVATE;

}



추가하고..


MyView.h에


afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message);


를 추가했더니..!! 해결이 되었습니다.. ^^

출처 : 데브피아
6시간 동안 헤메서 겨우 해결책을 찾았음.
일반 다이얼로그 기반에서는 쉽게 되는데 SDI 기반에서는 함수를 추가해줘야 정상 작동

Posted by system
l

Dialog에 View를 붙이면

Dialog Base프로젝트에 View를 붙여보자

예)
1. Dialog base로 이름이 ViewTest라는 프로젝트를 생성해 보자..
CViewTestApp, CViewTestDlg 라는 클래스가 생긴다..

2. Dialog에 붙일 View를 생성해보자..
CTestView 클래스를 생성하고 CSrollView에서 상속을 받자..
(View는 ScrollView로 테스트 해보자.. 일반뷰도 마찬가지다..)

3. View도 만들어 졌으면..
ViewTestDlg.cpp에 View를 include하고
OnCreate()에 다음과 같이 추가해 보자..

CRuntimeClass  *pObject;
pObject = RUNTIME_CLASS( CTestScrollView );

CTestScrollView* pView = (CTestScrollView*) pObject->CreateObject();

if (!pView->Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
    CRect(0, 0, 200, 200), this, AFX_IDW_PANE_FIRST, NULL))
{
   TRACE0("Failed to create view window\n");
   return -1;
}


이렇게 하고, 테스트를 해보자..그럼 ScrollView거 Dialog에 붙은것을 볼 수 있을 것이다.
View의 생성이 Protected로 되어 있기 때문에 View를 멤버로 가지고 Create를 통해서 생성을 하면 안된다.. 물론, view의 생성자를 Public으로 고치고 하면 생성이야 되겠지만 Close할때 문제가 생길 수 있다.

출처 : http://ninvu.egloos.com/2761264
Posted by system
l
Window는 뭔가 새로 그려야할 필요성 있을 때마다 WM_PAINT Message를 받습니다. OnPaint라는 이름으로 WM_PAINT에 대한 Handler Function이 보통 만들어지죠. System으로부터 WM_PAINT가 날아오는 상황은 다음과 같습니다.

    - 윈도우가 처음 생성되었을 때
    - 윈도우의 위치가 이동되었을 때 
    - 윈도우의 크기가 변경되었을 때(최소 및 최대화 포함)
    - 윈도우의 전체 또는 일부가 다른 윈도우에 가려져 있다가 나타날 때
    - 윈도우가 스크롤 될 때
    - UpdateWindow나 RedrawWindow 함수가 불렸을 때
    - InvalidateRect나 InvalidateRgn 함수가 불려서 다시 그려져야할 영역이 발생 한 후,
      Message Queue에 다른 처리할 Windows Message가 없을 때

그런데 WM_PAINT가 날아오기 '전'에 대부분 같이 따라오는 Message가 있습니다 WM_ERASEBKGND라는 것으로, Erase Background 라는 의미죠. 즉, 배경을 지워라.

Window의 기본 Message Procedure(DefWindowProc)는 사용자가 WM_ERASEBKGND를 받고도 아무 처리를 하지 않으면, WNDCLASS의 hbrBackground 맴버에 정의된 색상으로 배경을 지워버립니다. 깜빡이는 것은 아래 처럼 되기 때문에 발생하는 것이지요.

    1. WM_ERASEBKGND 받음
    2. 배경 지움
    3. WM_PAINT 받음
    4. Image 다시 그림

2까지가 '깜'이고 4까지 가면 '빡'이 됩니다. 깜빡 깜빡의 실체는 이것입니다.
손쉬운 처리는 WM_ERASEBKGND를 받았을 때, 배경을 안지우도록 하는 방법입니다. 보통 OnEraseBkgnd 정도의 이름을 갖게 되는 WM_ERASEBKGND Message Handler에서 0을 return 하면 됩니다.

    BOOL CAboutDlg::OnEraseBkgnd(CDC* pDC)
    {
        return 0;
    }

깜빡 거리는 것이 WM_PAINT Message Handler에서 그려주는 어떤 것이 아니라, 또 다른 Window인 '자식' Control이라면, Window Styles 중에 WS_CLIPCHILDREN Style을 '부모' Window에 먹여서 자식 Control에 의해 가려지는 영역은 그리기 대상에서 아예 제외시켜버리는 것이 일반적인 해결책입니다.

출처 : 데브피아 ( 박재민(MAXIST) )
Posted by system
l

< String을 숫자로>

//Convert a string to double (atof and _wtof), integer (atoi, _atoi64, _wtoi and _wtoi64), or long integer (atol and _wtol).

n      CString → int

       CString str = “100”;

       Int x = atoi (str);

      int n = atoi( "1234" );

             CString str("777");
               if(EOF == sscanf(str, "%d", &i)){      //error   }

 

n      CString → float

       CString str = “100.01”;

float x = atof (str);

             const char* str = "333.3";   
                               float x;
                        if(EOF == sscanf(str, "%f", &x)){      //error   }
             CString str = “-2.353”; 
                               float x = atof ( (LPCTSTR) str);
 

n      Char * → int

       char* string = "777";

         int x; 

     if(EOF == sscanf(string, "%d", &x)){      //error   }

            char* string = "777";
         int x = atoi(string);
            char * string = “777”
int x = strtol(string); 

 

n      Char * → float

            char* string = "333.3";
                              float x;
                              if(EOF == sscanf(string, "%f", &x)){      //error   }
            char* string = "333.3";
                              float x = atof(string);

       char * string = “333.3”;

     float x = strtod(string); // strtod 는 win95와 winNT에만 쓰인다?

 

 

<숫자를 CString으로>

n      int → CString ; ATL 의 CString도 동일

               int x = 1234; 
            CString str;

str.Format("%d", x); // %d 는 singed decimal integer의미 %i 와 같다.

                               //  unsinged decimal integer 는 %u

               // CString str;  str.Format("%d", 1234); 로 쓸 수도 있다.
               Ex2 )        long b1X  = 100; 
                               long  b1Y = 20;

 

                            CString strX;

                            strX.Format(L"X is %d     ", b1X);

                            CString strY;

                            strY.Format(L"Y is %d", b1Y);

                            CString strMouse = strX + strY;

 

                            CComBSTR cbstrMouse = strMouse;

                            spTEST->put_innerText( cbstrMouse );

n      float → CString

float x = 20.34;

CString str;

str.Format("%f",x);

 

<숫자를 char*로>

n      int → char *      

       int Number = 234;
     char string[10];
     wsprintf(string,_T("%d"),Number);
     //::MessageBox(NULL, string, "Succeeded", MB_OK);
 
       int x= 1234;
               char string[10];// simply large enough - don't forget the 
                                     // extra byte needed for the trailing '/0' 

        sprintf(string, "%d", x);

 

       char string[10];
     _itoa(1234, string, 10); //  _itoa 는 int만 char*로 바꿀 수 있다. 
                              // int 1234를 10진수 표기로 char *인 string에 저장하라. 

   

n      float → char *

               float x= 12.34;
               char string[10]; // simply large enough - don't forget the 
                        // extra byte needed for the trailing '/0' 

    sprintf(string, "%f", x);

 

<문자열 끼리>

n      CString → char *

CString str (“abcd”);

char * string = str.GetBuffer(str.GetLength() );

 

n      char * → CString

               char * string = "Hello"; 이면
 
          CString str = “Hello”;
          CString str(string);
          CString str;  str = string;

 

 

n      CString을 16진 int로 바꾸기

I need to convert a string data with an Hexa value like : "0F8CBA" into a DWORD type to have at final : 0F8CBA someone can help me please :)

 

strtol Convert string to long integer

strtoul Convert string to unsigned long integer

 

Here is the simplest way. strtol 이용

const char * sz = "0F8CBA";

DWORD dw = strtol( sz, 16 );

 

또는 strtoul 이용

unsigned long strtoul(const char *s, char **endptr, int radix);

/* strtoul example */

#include <stdlib.h>

#include <stdio.h>

int main(void)

  

char *string = "87654321", *endptr;

unsigned long lnumber;  

lnumber = strtoul(string, &endptr, 10);  

printf("string = %s  long = %lu",   string, lnumber);  

return 0;

 

Data Conversion Reference


Author : V.Girish

Environment: Compiled using VC6.0 Sp3 and tested using Win95/98 WinNT4.0 and Win 2000

Here are a few data Conversions with small examples :-

PART ONE :- DECIMAL CONVERSIONS
Decimal To Hexa :-

Use _itoa( ) function and set radix to 16.

 
               char hexstring[10]; 
               int number = 30;
               itoa( number, hexstring, 16);
 
               In hexstring is 1e.
Hexa To Decimal :-
a)You can use strtol function and you can specify base. 
               
               char * hexstring= "ABCDEF";
               char * p;
               int number = strtol(hexstring, &p,16);
 
b) Or you can use this too
 
               bool HexToDecimal (char* HexNumber, int& Number)
               { 
                 char* pStopString; 
                 Number = strtol (HexNumber, &pStopString, 16);
                 return (bool)(Number != LONG_MAX);
               }
 
Decimal to Time :-
 
               char *DecToTime(float fTime, char *szTime)
               {
                 int nHrs, nMin, nSec;              
                 fTime *= 3600;
                 nHrs = (int)fTime / 3600;
                 nMin = (int)(fTime - nHrs * 3600) / 60;
                 nSec = (int)(fTime - nHrs * 3600 - nMin * 60);
                 wsprintf(szTime, "%02d.%02d.%02d Hrs.Min.Sec.", nHrs, nMin, nSec);
                 return szTime;
               }
PART TWO :- STRING CONVERSIONS
String to Hexa :-
 
               sscanf(string, %04X, &your_word16);
               // where string = your string and 04 = length of your string and X = hex
 
 
Hex to CString :-
 
               CString Str;
               unsigned char Write_Buff[1];
               Write_Buff[0] = 0x01;
               Str.Format("0x0%x",Write_Buff[0]);
 
 
COleVariant to CString :-
 
               CString strTemp;
               COleVariant Var;
               Var = "FirstName";
               strTemp = Var.bstrVal;
               AfxMessageBox(strTemp);
 
 
CString to Char Pointer :-
 
               a)            CString MyString = "ABCDEF";
                               char * szMyString = (char *) (LPCTSTR) MyString;
 
               b)            char *pBuffer = new char[1024];
                               CString strBuf = "Test";
                               pBuffer = strBuf.GetBuffer(sizeof(pBuffer));
 
 
 
Char Pointer to CString :-
 
               char * mystring = "12345";
               CString string = mystring;
 
 
Double to CString including the fractional part :- // MFC Cstring만 되는 듯
 
            CString strValue,strInt, strDecimal;
            int decimal,sign;
            double dValue = 4.125;
            strValue =  _fcvt(dValue,6,&decimal,&sign);
 
            // Now decimal contains 1 because there is only one digit before the .
            strInt = strValue.Left(decimal);     // strInt contains 4
            strDecimal = strValue.Mid(decimal);          // strDecimal contains 125
 
            CString strFinalVal;
            strFinalVal.Format("%s.%s",strInt,strDecimal);       // strFinalVal contains 4.125
 
 
Double To CString :-
 
            CString strValue;
            int decimal,sign;
            
            double dValue = 123456789101112;
            strValue =  _ecvt(dValue,15,&decimal,&sign);
 
               
CString To Double :-
 
               strValue = "121110987654321";
               dValue = atof(strValue);
 
 
CString to LPCSTR :-
 
               CString str1 = _T("My String");
               int nLen = str1.GetLength();
               LPCSTR lpszBuf = str1.GetBuffer(nLen);
               // here do something with lpszBuf...........
               str1.ReleaseBuffer();
 
 
CString to LPSTR :-
 
               CString str = _T("My String");
               int nLen = str.GetLength();
               LPTSTR lpszBuf = str.GetBuffer(nLen);
               // here do something with lpszBuf...........
               str.ReleaseBuffer();
               
CString to WCHAR* :-
 
               CString str = "A string here" ;
               LPWSTR lpszW = new WCHAR[255];
 
               LPTSTR lpStr = str.GetBuffer( str.GetLength() );
               int nLen = MultiByteToWideChar(CP_ACP, 0,lpStr, -1, NULL, NULL);
               MultiByteToWideChar(CP_ACP, 0,              lpStr, -1, lpszW, nLen);
               AFunctionUsesWCHAR( lpszW );
               delete[] lpszW;
 
 
 
LPTSTR to LPWSTR :-
 
               int nLen = MultiByteToWideChar(CP_ACP, 0, lptStr, -1, NULL, NULL);
               MultiByteToWideChar(CP_ACP, 0,              lptStr, -1, lpwStr, nLen);
 
 
string to BSTR
 
               string ss = "Girish";
               BSTR _bstr_home = A2BSTR(ss.c_str());
 
 
CString to BSTR :-
 
               CString str = "whatever" ;
               BSTR resultsString = str.AllocSysString(); 
 
 
_bstr_t to CString :-
 
 
               #include 
               #include 
               _bstr_t bsText("Hai Bayram");
               CString strName;
               W2A(bsText, strName.GetBuffer(256), 256);
               strName.ReleaseBuffer();
               AfxMessageBox(strName);
 
               char szFileName[256];
               GetModuleFileName(NULL,szFileName,256);
               AfxMessageBox(szFileName);
 
 
PART THREE :- CHARACTER ARRAYS
 
 
Char array to integer
 
               char MyArray[20];
               int nValue;
 
               nValue = atoi(MyArray);
 
 
 
Char array to float
 
               char MyArray[20];
               float fValue;
 
               fValue = atof(MyArray);
 
 
Char Pointer to double :-
 
               char *str = " -343.23 "; 
               double dVal; 
               dVal = atof( str );  
 
 
Char Pointer to integer :-
 
               char *str = " -343.23 "; 
               int iVal;
               iVal = atoi( str ); 
 
 
               
Char Pointer to long :-
 
               char *str = "99999"; 
               long lVal; 
               lVal = atol( str );
 
 
Char* to BSTR :-
 
               char * p = "whatever";
               _bstr_t bstr = p;
 
 
Float to WORD and Vice Versa :-
 
               float  fVar;
               WORD   wVar;
               fVar = 247.346;
               wVar = (WORD)fVar; //Converting from float to WORD. The value in wVar would be  247
               wVar = 247;
               fVar = (float)fVar; //Converting from WORD to float. The value in fVar would be  247.00
 
 
               As i get more conversions, i'll keep adding them to this list. If you have something to say , please
feel free to send me a mail. All luck and have a nice time.

출처 : http://blog.naver.com/jangtimjang?Redirect=Log&logNo=20005044146

Posted by system
l

BOOL CXXXXView::PreCreateWindow(CREATESTRUCT& cs)
{
   cs.lpszClass = AfxRegisterWndClass(0);
   return CView::PreCreateWindow(cs);
    return CHtmlView::PreCreateWindow(cs);
}

위처럼 PreCreateWindow함수에 빨간 코드부분은 추가하시면 됩니다.
자연히 아래 return부분은 필요없겠죠..

그럼 즐프~

출처 : 데브피아 질답란

Posted by system
l