본문 바로가기
API Programming

[API] 문자열 출력 TextOut() & DrawText()

by cod1ng 2024. 3. 7.

Win32 API에서 문자열 출력을 하기 위해서는 아래의 함수를 사용한다.

 

BOOL TextOut(HDC hdc,int nXStart,int nYStartm LPCTSTR lpString, int cbString);

첫 번째 인자는 DC의 핸들이고,

두 번째,세 번째 인자는 문자열이 출력될 X좌표,Y좌표이다. 윈도우의 작업영역 원점을 기준으로 한다.

네 번째 인자는 출력할 문자열을 담고 있는 문자열형 포인터이고

마지막 인자는 출력할 문자열의 길이이다.

 

		TextOut(hdc, 300, 10, str, _tcslen(str)); 
		
		ReleaseDC(hwnd, hdc);

 

스켈레톤 코드에 추가하면

//0307 Textout.cpp
#pragma comment (linker, "/subsystem:windows")

#include <Windows.h>
#include <tchar.h>

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_MOUSEMOVE:
	{
		POINTS pt = MAKEPOINTS(lParam);

		TCHAR str[50];
		wsprintf(str, TEXT("%d:%d"), pt.x, pt.y);

		HDC hdc = GetDC(hwnd);

		InvalidateRect(hwnd, 0, TRUE);  //큐에 WM_PAINT를 넣어준다.
		UpdateWindow(hwnd);				//큐에 WM_PAINT가 있을 때 즉각 실행
		TextOut(hdc, 300, 10, str, _tcslen(str));

		ReleaseDC(hwnd, hdc);

		return 0;
	}

	case WM_CREATE:
		return 0;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hwnd, msg, wParam, lParam);
}


int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE hPrev, LPTSTR lpCmdLine, int nShowCmd)
{
	WNDCLASS wc;
	wc.cbWndExtra = 0;
	wc.cbClsExtra = 0;
	wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.hCursor = LoadCursor(0, IDC_ARROW);
	wc.hIcon = LoadIcon(0, IDI_APPLICATION);
	wc.hInstance = hInst;
	wc.lpfnWndProc = WndProc;
	wc.lpszClassName = TEXT("First");
	wc.lpszMenuName = 0;
	wc.style = 0;

	RegisterClass(&wc);

	HWND hwnd = CreateWindowEx(0, TEXT("First"), TEXT("Hello"), WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, 500, 500, 0, 0, hInst, 0);

	ShowWindow(hwnd, SW_SHOW);
	//UpdateWindow(hwnd);

	MSG msg;
	while (GetMessage(&msg, 0, 0, 0))
	{
		//TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0;
}

 

이런식으로 마우스의 위치에따라 좌표가 출력된다.