LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
TCHAR szBuffer[1];
switch (message)
{
case WM_CHAR:
szBuffer[1] = (TCHAR) wParam;
cout << wParam << " " << szBuffer[1] << " ";
break;
case WM_PAINT:
InvalidateRect(hwnd, NULL, TRUE);
hdc = BeginPaint(hwnd, &ps);
SelectObject(hdc,GetStockObject(SYSTEM_FIXED_FONT));
TextOut(hdc, 1, 1, szBuffer, 1);
EndPaint(hwnd, &ps);
return 0;
Hello all, I am trying to run the above code and simply print a single letter at a time on my window. However, I cannot seem to get the characters to appear on the window with the TextOut function but am able to display the characters in the terminal window. I am new to WinApi and am lost!
thanks in advance!
Your
szBuffer
is local toWndProc()
and by default local variables in C have automatic storage: each time yourWndProc()
is called, a newszBuffer
is created, so by the time yourWM_PAINT
is reached, whatever was typed inWM_CHAR
was lost. You will need to storeszBuffer
somewhere else, such as outsideWndProc()
, or declare it asstatic
, which will keep the buffer around (but beware that static storage is NOT safe for recursion).Also in C the first element of an array has index 0, not 1; the line
szBuffer[1] = (TCHAR) wParam;
needs to beszBuffer[0] = (TCHAR) wParam;
to do what you want.Since I am running on the assumption you are new to C, see Jonathan Potter's comment about having an extra character in your strings whose value is zero (not the character code for the digit zero, but the numerical value 0, or
'\0'
orL'\0'
). WhileTextOut()
and the other GDI text drawing functions don't use these null-terminated strings, everything else in C does. Watch out.And Joe Willcoxson's comment is also correct.
InvalidateRect()
queues the given rectangle as needing repaint. Using it in yourWM_PAINT
handler will cause you to always getWM_PAINT
messages over and over again, which will have negative effects on performance as your programs become larger and larger.