win32 콘솔 app에서 간단하게 window 창 만들기

본 글은 win32 콘솔 모드 application에서 win32 api를 사용하여 윈도우를 만드는 방법을 싣고 있다.

윈도우에서 전체 솔루션의 부분 기능 테스트 등 테스트 application을 만드는 경우 win32 콘솔 모드를 자주 사용하곤 한다. 가끔 이 콘솔 모드의 test application에서 윈도우를 띄워 이미지나 그래프를 볼필요가 있을 때가 있다. 아래는 win32 API를 사용해 windows를 띄우는 예제 코드다.
CreateWindowEx를 사용해 윈도우를 생성한다. 윈도우 생성 전 windows class 등록이 필요하다. 클래스 등록은 아래와 같이 간단하게 할 수 있으며, 세가지 요소(인스턴스, 클래스 이름, 메시지 프로시저)는 꼭 들어가야 한다. 
WNDCLASS wc = {};

wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);

인스턴스는 GetModuleHandle을 사용해 받아오면 되고, 클래스 이름은 다른 윈도우와 구분가능한 이름을 정해 주면 된다. 윈도우 메시지 프로시저는 LRESULT CALLBACK WindowProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)의 형태로 만들면 된다. 
CreateWindowEx를 통해 윈도우 생성 후 ShowWindow(hwnd, SW_SHOW);를 사용해 윈도우를 화면에 보이도록 해야 하며, message를 처리하는 while루프를 만들어야 한다. DispatchMessage를 호출할 때 마다, WindowProc 함수가 호출되어 메시지를 처리하게 된다.


#include <Windows.h>

LRESULT CALLBACK WindowProc(HWND hwnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
static HBRUSH hbrGreen;

switch (Msg)
{
case WM_CREATE:
hbrGreen = CreateSolidBrush(RGB(0, 150, 0));
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
RECT rect = { 10, 10, 20, 20 };
RECT textrect = { 10, 25, 640, 480 };
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &rect, hbrGreen);
SetTextColor(hdc, RGB(0, 0, 150));
DrawText(hdc, TEXT("ryanclaire.blogspot.com"), 23, &textrect, DT_LEFT | DT_TOP);
EndPaint(hwnd, &ps);
}
return 0;
case WM_DESTROY:
DeleteObject(hbrGreen);
PostQuitMessage(0);
return 0;
}

return DefWindowProc(hwnd, Msg, wParam, lParam);
}

int createwindow_example()
{
MSG msg;
HINSTANCE hInstance = GetModuleHandle(NULL);
const wchar_t CLASS_NAME[] = L"Ryan Window Class";
WNDCLASS wc = {};

wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);

HWND hwnd = CreateWindowEx(
0,                              // Optional window styles.
CLASS_NAME,                     // Window class
L"Ryan's Example Windows",    // Window text
(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU),            // Window style
CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, // Size and position
NULL,       // Parent window    
NULL,       // Menu
hInstance,  // Instance handle
NULL        // Additional application data
);

if (hwnd == NULL)
{
return 0;
}

ShowWindow(hwnd, SW_SHOW);

while (GetMessage(&msg, (HWND)NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return msg.wParam;
}

위 코드를 실행하면 아래와 같이 윈도우가 생성된다. 

  

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

base64 인코딩 디코딩 예제 c 소스

간단한 칼만 필터(Kalman Filter) 소스 코드와 사용 예제