textout winapi with keyboard messages

120 views Asked by At
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!

1

There are 1 answers

0
andlabs On

Your szBuffer is local to WndProc() and by default local variables in C have automatic storage: each time your WndProc() is called, a new szBuffer is created, so by the time your WM_PAINT is reached, whatever was typed in WM_CHARwas lost. You will need to store szBuffer somewhere else, such as outside WndProc(), or declare it as static, 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 be szBuffer[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' or L'\0'). While TextOut() 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 your WM_PAINT handler will cause you to always get WM_PAINT messages over and over again, which will have negative effects on performance as your programs become larger and larger.