To draw text on the screen using C++, you can make use of the Win32 API functions. Here's an example code that demonstrates how to draw text on the screen:
#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// Set the font properties
HFONT font = CreateFont(30, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Arial");
SelectObject(hdc, font);
// Draw the text
TextOut(hdc, 10, 10, L"Hello World", 11);
// Clean up
DeleteObject(font);
EndPaint(hwnd, &ps);
}
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Register the window class
WNDCLASS wc{};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"MyWindowClass";
RegisterClass(&wc);
// Create the window
HWND hwnd = CreateWindowEx(0, wc.lpszClassName, L"My Window", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, nullptr, nullptr, hInstance, nullptr);
if (hwnd == nullptr)
return 0;
// Show the window
ShowWindow(hwnd, nCmdShow);
// Message loop
MSG msg{};
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
In this code, the main logic lies in the WindowProc function, which serves as the window procedure for the application. In the WM_PAINT message handler, we create a font using CreateFont and select it into the device context (hdc) using SelectObject. Then, we use TextOut to draw the desired text at the specified coordinates (10, 10 in this case).
The WinMain function handles the creation and display of the window, and the message loop using GetMessage.
Make sure to provide the necessary include statements and link the required libraries (e.g., gdi32.lib, user32.lib) to successfully compile the code.
Feel free to modify the font properties and the text string as needed to suit your requirements.