Programming/C++

c++ winmain

fishersheep 2021. 8. 15. 17:34
반응형
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int);
bool createMainWindow(HINSTANCE, int);
LRESULT WINAPI WinProc(HWND, UINT, WPARAM, LPARAM);

//전역변수
HINSTANCE hinst;

//상수
const char CLASS_NAME[] = "WinMain";
const char APP_TITLE[] = "Hello World";
const int WINDOW_WIDTH = 400;
const int WINDOW_HEIGHT = 400;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	MSG msg;
	//윈도우생성
	if (!CreateWindow(hInstance, nCmdShow))
		return false;
	//메인 메시지 루프
	int done = 0;
	while (!done)
	{
		//peekmessage는 윈도우 메시지를 확인하는 논블로킹 메소드다.
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			//종료메시지를 찾는다.
			if (msg.message == WM_QUIT)
				done = 1;
			//해석한뒤 메시지를 winproc에 전달한다.
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	return msg.wParam;
}

LRESULT WINAPI Winproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_DESTROY:
		//윈도우에게 이프로그램을 종료하라고 알린다.
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hWnd, msg, wParam, lParam);
}

bool CreateMainWindow(HINSTANCE hInstacne, int nCmdShow)
{
	WNDCLASSEX wcex;
	HWND hwnd;

	//window 클래스 구조체를 메인 윈도우에 대한 매개변수로 채운다.

	wcex.cbSize = sizeof(wcex);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WinProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = NULL;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);

	//배경 브러시
	wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wcex.lpszMenuName = NULL;
	wcex.lpszClassName = CLASS_NAME;
	wcex.hIconSm = NULL;

	//window 클래스를 등록한다.
	//registerclassex함수는 에러가 발생할 경우 0을 반환한다.

	if (RegisterClassEx(&wcex) == 0)
		return false;


	HWND hWnd = CreateWindowW(
		CLASS_NAME,
		APP_TITLE,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		WINDOW_WIDTH,
		WINDOW_HEIGHT,
		(HWND)NULL,
		(HWND)NULL,
		hInstance,
		(LPVOID)NULL
	);

	if (!hwnd)
		return false;

	ShowWindow(hwnd, nCmdShow);
	UpdateWindow(hwnd);
	return true;
}
반응형