2007년 4월 24일 화요일

Elisha Cuthbert






Elisha Cuthbert






Elisha Cuthbert






Elisha Cuthbert

Hey, she's back!!!



2007년 4월 23일 월요일

MemDC를 이용한 비트맵 출력

// OnDraw(CDC* pDC) 내에서 경우

CDC MemDC;
MemDC.CreateCompatibleDC(pDC);

CBitmap bitmap;
bitmap.LoadBitmap(IDB_ME); // Bitmap 리소스
CBitmap *pOldBitmap = (CBitmap *)MemDC.SelectObject(&bitmap);

pDC->BitBlt(0, 0, 100, 100, &MemDC, 0, 0, SRCCOPY);

MemDC.SelectObject(pOldBitmap);

// End

별그리기 (CRgn)

// 다각형의 모양을 가지는 점들의 집합을 준비합니다.
// 여기는 별만 그리지만 삼각형도 똑 같습니다.
// 그리는 모양은 마음대로 바꾸세요.
CPoint points[11];

// 72' 씩 회전된 꼭지점으로 이루어진 점 생성
// 여기서 알아서 모양을 만드세요.
double Pi = 3.14159265359;

for ( int i = 0; i < 10; i += 2 )
{
// 별의 바깥쪽 꼭지점 (큰 반지름으로 만듬)
points[i].x = (long)(25*cos((double)(i*72*Pi)/360.0));
points[i].y = (long)(25*sin((double)(i*72*Pi)/360.0));

// 별의 안쪽 꼭지점 (작은 반지름으로 만듬)
points[i+1].x = (long)(10*cos((double)((i+1)*72*Pi)/360.0));
points[i+1].y = (long)(10*sin((double)((i+1)*72*Pi)/360.0));
}

// 끝점은 첫점과 같게 맞춤니다.
points[10] = points[0];

CRgn rgnStar;
rgnStar.CreatePolygonRgn(points, 11, WINDING);

// 클라이언트 영역을 가져옵니다.
CRect r;
GetClientRect(&r);

// 그림 그릴 브러시를 초기화합니다.
CBrush brush;
brush.CreateSolidBrush(RGB(0,0,0));

// 영역을 초기화 합니다.
CRgn rgn;
rgn.CreateRectRgn(0, 0, 0, 0);
rgn.CopyRgn(&rgnStar);
rgn.OffsetRgn(point.x, point.y);

// 별을 그립니다.
dc.FillRgn(&rgn, &brush);

데스크탑윈도우의 DC를 얻어서 사용하는 방법

Very simple, uhh~

CRect r;
GetClientRect(&r);
CClientDC desktopDC(GetDesktopWindow());
pDC->BitBlt(0, 0, r.Width(), r.Height(), &desktopDC, 0, 0, SRCCOPY);

2007년 4월 19일 목요일

Using DirectX with MFC (2)

DirectX는 제대로 설치되어 있다고 가정한다.

SDI로 App 를 생성하고 Document/View Architecture 를 Uncheck 한다.
기타 원하는 대로 만든다.

프로젝트가 생성이 되면 ChildView.h 및 ChildView.cpp 를 삭제한다.
DirectX 프로그래밍에서는 별도의 View가 필요가 없다.

MainFrm.h 에서

#include "ChildView.h"

를 삭제한다. 그 다음

CMainFrame 내의

CChildView m_wndView;

도 삭제한다.

CMainFrame::OnCreate() 내의

// create a view to occupy the client area of the frame
if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW,
CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
{
TRACE0("Failed to create view window\n");
return -1;
}

부분을 삭제하고 대신

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;


/////////////////////////////////////////////////////////////////////
// 여기에DirectX의초기화를수행한다.
/////////////////////////////////////////////////////////////////////
HWND hDevice, hFocus;
HRESULT hr;

hDevice = GetSafeHwnd();
hFocus = GetTopLevelParent() ->GetSafeHwnd();

GetClientRect(&m_rectClient);

// Create Direct3D object
m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

D3DDISPLAYMODE d3ddm;
m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm);

// D3DPRESENT_PARAMETERS 구조체의설정
::ZeroMemory(&m_d3dpp, sizeof(m_d3dpp));
m_d3dpp.Windowed = TRUE;
m_d3dpp.BackBufferCount = 1;
m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
m_d3dpp.EnableAutoDepthStencil = TRUE;
m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
m_d3dpp.hDeviceWindow = hDevice;
m_d3dpp.BackBufferWidth = m_rectClient.Width();
m_d3dpp.BackBufferHeight = m_rectClient.Height();
m_d3dpp.BackBufferFormat = d3ddm.Format;
m_d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;

// 디바이스작성
hr = m_pD3D->CreateDevice(
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hFocus,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&m_d3dpp,
&m_pd3dDevice
);

m_pd3dDevice->SetDialogBoxMode(TRUE);
m_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);

////////////////////////////////////////////////////////////////////
// 여기까지DirectX의초기화부분임
////////////////////////////////////////////////////////////////////

return 0;
}

와 같이 필요한 초기화를 수행한다.

CMainFrame::OnSetFocus() 함수를 삭제한다.
CMainFrame::OnCmdMsg() 함수를 삭제한다.



“stdafx.h” 에 다음 줄들을 추가한다.
그때 그때 필요한 부분을 알아서 추가해야 한다.

필요한 헤더 파일들과 링크할 라이브러리 파일들이다.

// Direct3D includes
#include
#include
#include

// DirectSound includes
#include
#include
#include

#pragma comment( lib, "dxerr.lib" )
#pragma comment( lib, "dxguid.lib" )
#if defined(DEBUG) defined(_DEBUG)
#pragma comment( lib, "d3dx9d.lib" )
#else
#pragma comment( lib, "d3dx9.lib" )
#endif
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "winmm.lib" )
#pragma comment( lib, "comctl32.lib" )


CMainFrame 의 헤더파일에 아래를 추가한다.

// Attributes
public:
CRect m_rectClient; // Client window size
IDirect3D9* m_pD3D; // The IDirect3D9 interface
IDirect3DDevice9* m_pd3dDevice; // D3D Device
D3DPRESENT_PARAMETERS m_d3dpp; // The present parameters.
bool m_bReady; // Is DX9 ready to render?

// Operations
public:
void Render(); // Render


Constructor에서 필요한 초기화를 수행한다.

CMainFrame::CMainFrame()
{
// 필요한초기화를수행한다.
m_pD3D = NULL;
m_pd3dDevice = NULL;
m_bReady = false;
}

ReleaseAllObject() 라는 함수를 하나 만들고 아래와 같이 추가한다.

void CMainFrame::ReleaseAllObject()
{
// DirectX가시동되었으면삭제
if ( m_pD3D != NULL )
{
if ( m_pd3dDevice != NULL)
{
m_pd3dDevice->Release();
m_pd3dDevice = NULL;
}
m_pD3D->Release();
m_pD3D = NULL;
}
}

WM_ACTIVATEAPP 의 Event handler 를 만들고 아래를 추가한다.

void CMainFrame::OnActivateApp(BOOL bActive, DWORD dwThreadID)
{
CFrameWnd::OnActivateApp(bActive, dwThreadID);

// 준비 완료
m_bReady = bActive;
}

WM_DESTROY 의 Event handler 를 만들어 주고 아래를 추가한다.

void CMainFrame::OnDestroy()
{
ReleaseAllObject();

CFrameWnd::OnDestroy();

// TODO: Add your message handler code here

}

당연히 Render() 함수도 구현해 준다.

void CMainFrame::Render()
{
m_pd3dDevice->Clear(
0,
NULL,
D3DCLEAR_TARGET D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0, 0, 0),
1.0f,
0
);

if(SUCCEEDED(m_pd3dDevice->BeginScene()))
{
m_pd3dDevice->EndScene();
}

m_pd3dDevice->Present(NULL, NULL, NULL, NULL);
}

이제 Test 겸 다음과 같이 실행해 본다.

void CMainFrame::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CFrameWnd::OnPaint() for painting messages
Render();
}

검은 색 화면이 나오면 일단 성공한 것이다.

Using DirectX with MFC

우선 “stdafx.h”에

// Direct3D includes
#include <d3d9.h>
#include <d3dx9.h>
#include <dxerr.h>

// DirectSound includes
#include <mmsystem.h>
#include <mmreg.h>
#include <dsound.h>

#pragma comment( lib, "dxerr.lib" )
#pragma comment( lib, "dxguid.lib" )
#if defined(DEBUG) || defined(_DEBUG)
#pragma comment( lib, "d3dx9d.lib" )
#else
#pragma comment( lib, "d3dx9.lib" )
#endif
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "winmm.lib" )
#pragma comment( lib, "comctl32.lib" )

를 추가한다. 그때 그때 필요한 헤더파일과 라이브러리를 포함해야 한다.

그리고 XXXView.h 파일을 열고 아래 내용들을 추가한다.

CRect m_rectClient;         // Client window size
IDirect3D9* m_pD3D;         // The IDirect3D9 interface
IDirect3DDevice9* m_pd3dDevice; // D3D Device
D3DPRESENT_PARAMETERS m_d3dpp;  // The present parameters.
bool m_bReady;          // Is DX9 ready to render?
void Render();          // Render


XXXView.cpp 파일을 열고 OnInitialUpdate() 함수를 override하고 아래 내용을 추가한다.

void XXXView::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    // TODO: Add your specialized code here and/or call the base class
    HWND hDevice, hFocus; 
HRESULT hr; 

hDevice = GetSafeHwnd(); 
hFocus  = GetTopLevelParent() ->GetSafeHwnd(); 

GetClientRect(&m_rectClient); 

// Create Direct3D object
        m_pD3D = Direct3DCreate9(D3D_SDK_VERSION); 

D3DDISPLAYMODE d3ddm; 
m_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm); 

// D3DPRESENT_PARAMETERS 구조체의설정
::ZeroMemory(&m_d3dpp, sizeof(m_d3dpp)); 
m_d3dpp.Windowed            = TRUE; 
m_d3dpp.BackBufferCount     = 1; 
m_d3dpp.SwapEffect          = D3DSWAPEFFECT_DISCARD; 
m_d3dpp.EnableAutoDepthStencil  = TRUE; 
m_d3dpp.AutoDepthStencilFormat  = D3DFMT_D16; 
m_d3dpp.hDeviceWindow       = hDevice; 
m_d3dpp.BackBufferWidth     = m_rectClient.Width(); 
m_d3dpp.BackBufferHeight        = m_rectClient.Height(); 
m_d3dpp.BackBufferFormat        = d3ddm.Format
m_d3dpp.Flags                 |= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;

// 디바이스작성
hr = m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, 
D3DDEVTYPE_HAL, 
hFocus, 
D3DCREATE_SOFTWARE_VERTEXPROCESSING, 
&m_d3dpp, 
&m_pd3dDevice);

    m_pd3dDevice->SetDialogBoxMode(TRUE);
    m_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);

m_bReady = TRUE;
}

Render() 함수는 아래와 같다.

void CeConsoleView::Render()
{
m_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

    if(SUCCEEDED(m_pd3dDevice->BeginScene())) 
    {
        m_pd3dDevice->EndScene(); 
    }

    m_pd3dDevice->Present(NULL, NULL, NULL, NULL);
}

마지막으로 OnDraw() 함수에 아래 내용을 추가하면 준비는 완료

    // TODO: add draw code for native data here
    if( m_bReady )
        Render();


2007년 4월 16일 월요일

Using DirectShow

Getting the SDK package

At the first stage, you have to download following DirectSDK which of version is
February 2005.

http://www.microsoft.com/downloads/details.aspx?FamilyID=8af0afa9-1383-44b4-bc8b-7d6315212323&DisplayLang=en

Then install the extra package in the appropriate directory.

Setting the environmental variables

In the VS.NET, select Tools>Options>VC++ Directories.

Add the include/lib directory in the "Include files" and "Library files".
You can find them in the combo box.

Using the SDK

Test with next code. If there's no error when compiling and excuting, all done.




#include <DShow.h>

#pragma comment(lib, "strmiids.lib")

void main(void)
{
    IGraphBuilder *pGraph = NULL;
    IMediaControl *pControl = NULL;
    IMediaEvent   *pEvent = NULL;

    // Initialize the COM library.
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr))
    {
        printf("ERROR - Could not initialize COM library");
        return;
    }

    // Create the filter graph manager and query for interfaces.
    hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, 
                        IID_IGraphBuilder, (void **)&pGraph);
    if (FAILED(hr))
    {
        printf("ERROR - Could not create the Filter Graph Manager.");
        return;
    }

    hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

    // Build the graph. IMPORTANT: Change this string to a file on your system.
    hr = pGraph->RenderFile(L"C:\\Example.avi", NULL);
    if (SUCCEEDED(hr))
    {
        // Run the graph.
        hr = pControl->Run();
        if (SUCCEEDED(hr))
        {
            // Wait for completion.
            long evCode;
            pEvent->WaitForCompletion(INFINITE, &evCode);

            // Note: Do not use INFINITE in a real application, because it
            // can block indefinitely.
        }
    }
    pControl->Release();
    pEvent->Release();
    pGraph->Release();
    CoUninitialize();
}

2007년 4월 12일 목요일

Sierpinski Carpet Demo



void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    CRect clientRect;
    GetClientRect(&clientRect);
    SolidBrush brush(Color(255, 0, 0, 0));

    SierpinskiCarpet3(g, brush, clientRect.Width()/2, clientRect.Height()/2, 120);

}

void CGdiplusDemoView::SierpinskiCarpet1(Graphics& g, SolidBrush& brush, int x, int y, int r)
{
    if ( r <= 0 )
        return;

    SierpinskiCarpet1(g, brush, x-2*r, y+2*r, r/3);
    SierpinskiCarpet1(g, brush, x-2*r, y, r/3);
    SierpinskiCarpet1(g, brush, x-2*r, y-2*r, r/3);
    SierpinskiCarpet1(g, brush, x, y+2*r, r/3);
    SierpinskiCarpet1(g, brush, x, y-2*r, r/3);
    SierpinskiCarpet1(g, brush, x+2*r, y+2*r, r/3);
    SierpinskiCarpet1(g, brush, x+2*r, y, r/3);
    SierpinskiCarpet1(g, brush, x+2*r, y-2*r, r/3);
    g.FillRectangle(&brush, x-r/4, y-r/4, r/2, r/2);
}

void CGdiplusDemoView::SierpinskiCarpet2(Graphics& g, SolidBrush& brush, int x, int y, int r)
{
    if ( r <= 0 )
        return;

    SierpinskiCarpet2(g, brush, x-2*r, y+2*r, r/2);
    SierpinskiCarpet2(g, brush, x-2*r, y, r/2);
    SierpinskiCarpet2(g, brush, x-2*r, y-2*r, r/2);
    SierpinskiCarpet2(g, brush, x, y+2*r, r/2);
    SierpinskiCarpet2(g, brush, x, y-2*r, r/2);
    SierpinskiCarpet2(g, brush, x+2*r, y+2*r, r/2);
    SierpinskiCarpet2(g, brush, x+2*r, y, r/2);
    SierpinskiCarpet2(g, brush, x+2*r, y-2*r, r/2);
    g.FillRectangle(&brush, x-r/4, y-r/4, r/2, r/2);
}

void CGdiplusDemoView::SierpinskiCarpet3(Graphics& g, SolidBrush& brush, int x, int y, int r)
{
    if ( r <= 0 )
        return;

    SierpinskiCarpet3(g, brush, x-r, y+r, r/2);
    SierpinskiCarpet3(g, brush, x+r, y+r, r/2);
    SierpinskiCarpet3(g, brush, x-r, y-r, r/2);
    SierpinskiCarpet3(g, brush, x+r, y-r, r/2);
    g.FillRectangle(&brush, x-r/3, y-r/3, r/3, r/3);
}


2007년 4월 10일 화요일

CInternetSession, CHttpConnection, CHttpFile 예제

#include "stdafx.h"
#include "main.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

using namespace std;

void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]);
void Say(CString status);

int TMainApp(int argc, TCHAR* argv[], TCHAR* envp[]) {

    Say("Parsing command line...");
    ParseCmdLine(argc, argv, envp);

    Say("Allocating variables...");
    CString m_sURL = "http://www.digital.go.kr/rss/fc_textxml.jsp?row=120&col=61®ion=7&locationcode=4111573000";
    CInternetSession m_Session;
    CHttpConnection* m_pHttpConnection=NULL;
    CHttpFile* m_pHttpFile = NULL;

    Say("Connecting...");
    try {
        m_pHttpConnection = m_Session.GetHttpConnection(m_sURL,(INTERNET_PORT)80, NULL, NULL);
        if( m_pHttpConnection == NULL )
            throw CString("Http connection failed");

        m_pHttpFile = (CHttpFile*)m_Session.OpenURL(m_sURL);
    
        if( !m_pHttpFile ) {
            m_pHttpFile->Close();
            delete m_pHttpFile;
            throw CString("HttpFile connection failed");
        }
    }
    catch ( CInternetException *pEx ) {
        if ( m_pHttpFile) {
            m_pHttpFile->Close();
            delete m_pHttpFile;
        }
        if ( m_pHttpConnection ) {
            m_pHttpConnection->Close();
            delete m_pHttpConnection;
        }
        TCHAR lpszErrorMessage[255];
        pEx->GetErrorMessage(lpszErrorMessage, 255);
        pEx->Delete();
        cout << lpszErrorMessage << endl;
        return 1;
    }
    catch (CString e) {
        cout << "Error : " << (LPCTSTR)e << endl;
        cout << "Program aborted..." << endl;
        return -1;
    }
    Say("Connection established.");

    Say("Listing file...");
    CString line;
    while ( m_pHttpFile->ReadString(line) != NULL ) {
        // line += "\r\n";
        wcout << (LPCTSTR)line << endl;
    }
    Say("Listing complete");

    Say("Shutdown process started");
    Say("Deleting m_pHttpFile...");
    if ( m_pHttpFile) {
        m_pHttpFile->Close();
        delete m_pHttpFile;
    }
    Say("Deleting m_pHttpConnection...");
    if ( m_pHttpConnection ) {
        m_pHttpConnection->Close();
        delete m_pHttpConnection;
    }

    return 0;
}

void ParseCmdLine(int argc, TCHAR* argv[], TCHAR* envp[]) {

//  if ( argc != 2 )
//      throw CString(L"Usage : inet.exe ip_address");

}

void Say(CString status) {
    cout << (LPCTSTR)status << endl;
}


2007년 4월 8일 일요일

MFC Using registry key

리지스트리 이용하기
Using registry key

InitInstance()에

    ...
    SetRegistryKey(_T("My App"));
    ...
    
라고 하면

    HKEY_CURRENT_USER\Software\My App\(Project name)
    
아래에 저장된다.


이것은 Demo only로 OnDraw에 이런 짓은 하지 말기를...
AfxGetApp()->WriteProfileXXX()
AfxGetApp()->GetProfileXXX()
함수 참조

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);
    CString sTest;

    AfxGetApp()->WriteProfileString(L"Section", L"Entry", L"Value");

    // Create font
    FontFamily fontFamily(L"Arial");
    Font font(&fontFamily, 24, FontStyleBold, UnitPixel);

    // Create brush
    SolidBrush brush(Color(255, 0, 0, 255));

    // Center alignment
    StringFormat stringFormat;
    stringFormat.SetAlignment(StringAlignmentCenter);
    stringFormat.SetLineAlignment(StringAlignmentCenter);

    sTest = AfxGetApp()->GetProfileString(L"Section", L"Entry");
    PointF pointF(100, 100);
    g.DrawString(sTest, sTest.GetLength(), &font, pointF, &stringFormat, &brush);
}


Ogura Yuko

She's also hot girl...








GDI+ coordinate transform

이 예제는 Visual C++.NET programming Bible - Young Jin 에서 발췌한 것이다.

// OnInitialUpdate override

void CGdiplusDemoView::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    // TODO: Add your specialized code here and/or call the base class
    SetTimer(0, 100, NULL);
}

// OnTimer override

void CGdiplusDemoView::OnTimer(UINT_PTR nIDEvent)
{
    // TODO: Add your message handler code here and/or call default
    Invalidate();

    CView::OnTimer(nIDEvent);
}


#define R_SUN   50
#define R_EARTH 30
#define R_MOON  20

#define EARTH_TO_SUN    300
#define EARTH_TO_MOON   70

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    static int angleEarth, angleLunar;
    CRect rect;
    GetClientRect(rect);

    Pen pen(Color(255, 0, 0, 0), 3);
    SolidBrush brush(Color(255, 0, 0, 255));

    // Create font
    FontFamily fontFamily(L"Arial");
    Font font(&fontFamily, 12, FontStyleBold, UnitPixel);

    // Text output format
    StringFormat stringFormat;
    stringFormat.SetAlignment(StringAlignmentCenter);
    stringFormat.SetLineAlignment(StringAlignmentCenter);

    // Draw sun
    g.ResetTransform();
    g.TranslateTransform((REAL)rect.Width()/2, (REAL)rect.Height()/2);
    g.DrawEllipse(&pen, -R_SUN, -R_SUN, 2*R_SUN, 2*R_SUN);
    g.DrawString(L"SUN", 3, &font, PointF(0, 0), &stringFormat, &brush);

    // Draw earth
    g.RotateTransform((REAL)angleEarth);
    g.TranslateTransform(EARTH_TO_SUN, 0);
    g.DrawEllipse(&pen, -R_EARTH, -R_EARTH, 2*R_EARTH, 2*R_EARTH);
    g.DrawString(L"EARTH", 5, &font, PointF(0, 0), &stringFormat, &brush);

    // Draw moon
    g.RotateTransform((REAL)angleLunar);
    g.TranslateTransform(EARTH_TO_MOON, 0);
    g.DrawEllipse(&pen, -R_MOON, -R_MOON, 2*R_MOON, 2*R_MOON);
    g.DrawString(L"MOON", 4, &font, PointF(0, 0), &stringFormat, &brush);

    angleEarth++;
    angleLunar += 12;
}


GDI+ mapping mode

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    Pen pen(Color(255, 0, 0, 0), 3);

    /*
    enum Unit
    {
        UnitWorld,      // 0 -- World coordinate (non-physical unit)
        UnitDisplay,    // 1 -- Variable -- for PageTransform only
        UnitPixel,      // 2 -- Each unit is one device pixel.
        UnitPoint,      // 3 -- Each unit is a printer's point, or 1/72 inch.
        UnitInch,       // 4 -- Each unit is 1 inch.
        UnitDocument,   // 5 -- Each unit is 1/300 inch.
        UnitMillimeter  // 6 -- Each unit is 1 millimeter.
    };
    */

    // Pixel mapping
    g.SetPageUnit(UnitPixel);
    g.DrawRectangle(&pen, 30, 30, 60, 60);

    // Milimeter mapping
    g.SetPageUnit(UnitMillimeter);
    g.DrawRectangle(&pen, 30, 30, 60, 60);
}


GDI+ clipping region

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    // Create region
    Point points[] = {
        Point(10, 30), Point(200, 10), Point(150, 50), Point(170, 150)
    };
    GraphicsPath path;
    path.AddPolygon(points, 4);
    Region region(&path);

    // Draw region
    Pen pen(Color(255, 0, 0, 0));
    g.DrawPath(&pen, &path);

    // Clipping
    g.SetClip(®ion);

    // Display text
    FontFamily fontFamily(L"Arial");
    Font font(&fontFamily, 36, FontStyleBold, UnitPixel);
    SolidBrush brush(Color(255, 255, 0, 0));

    g.DrawString(L"Clipping", 20, &font, PointF(15, 25), &brush);
}


GDI+ text display

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    CRect rect;
    GetClientRect(rect);
    
    WCHAR string[] = L"Hi, I'm a man who used XT long time ago";

    /*
    enum FontStyle
    {
        FontStyleRegular    = 0,
        FontStyleBold       = 1,
        FontStyleItalic     = 2,
        FontStyleBoldItalic = 3,
        FontStyleUnderline  = 4,
        FontStyleStrikeout  = 8
    };
    enum Unit
    {
        UnitWorld,      // 0 -- World coordinate (non-physical unit)
        UnitDisplay,    // 1 -- Variable -- for PageTransform only
        UnitPixel,      // 2 -- Each unit is one device pixel.
        UnitPoint,      // 3 -- Each unit is a printer's point, or 1/72 inch.
        UnitInch,       // 4 -- Each unit is 1 inch.
        UnitDocument,   // 5 -- Each unit is 1/300 inch.
        UnitMillimeter  // 6 -- Each unit is 1 millimeter.
    };
    */

    // Create font
    FontFamily fontFamily(L"Arial");
    Font font(&fontFamily, 24, FontStyleBold, UnitPixel);

    // Create brush
    SolidBrush brush(Color(255, 0, 0, 255));

    // Center alignment
    StringFormat stringFormat;
    stringFormat.SetAlignment(StringAlignmentCenter);
    stringFormat.SetLineAlignment(StringAlignmentCenter);

    // Display text in the middle of the window
    PointF pointF(rect.Width()/2, rect.Height()/2);
    g.DrawString(string, (INT)wcslen(string), &font, pointF, &stringFormat, &brush);

    // Adjust display quality
    g.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);

    // Display text int the middle of the rectangle
    RectF rectF(300, 20, 200, 100);
    g.DrawString(string, (INT)wcslen(string), &font, rectF, &stringFormat, &brush);

    Pen pen(Color(255, 255, 0, 0));
    g.DrawRectangle(&pen, rectF);
}


GDI+ draw image

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    // Read image file, *.bmp, *.gif, *.png, *.jpg format supported
    Image image(L"test.jpg");
    int width = image.GetWidth();
    int height = image.GetHeight();

    // Display image
    g.DrawImage(&image, 10, 10, width, height);

    // Display distorted image
    Point points[] = {
        Point(250, 20), Point(150, 100), Point(300, 50)
    };
    g.DrawImage(&image, points, 3);

    // Magnified display
    g.SetInterpolationMode(InterpolationModeNearestNeighbor);
    g.DrawImage(&image, 10, 150, width*2, width*2);

    g.SetInterpolationMode(InterpolationModeHighQualityBilinear);
    g.DrawImage(&image, 220, 150, width*2, width*2);
}


GDI+ paint with pattern brush

void CGdiplusDemoView::OnDraw(CDC* pDC)
{
    Graphics g(pDC->m_hDC);

    for ( int i = 0; i < HatchStyleTotal; i++ ) {
        HatchBrush brush((Gdiplus::HatchStyle)i,
            Color(255, 0, 0, 0), Color(255, 255, 255, 0));
        g.FillRectangle(&brush, 20+(i%7)*90, 20+(i/7)*60, 80, 50);
    }
}