问题
I want a proper way in which I can output a character string and display it on a Window created. I had been using textout() function, but since it only paints the window, once the window is minimized and restored back, the data displayed on the window disappears. Also when the data to be displayed is exceeds the size of Window, only the data equal to window size is displayed and other data is truncated. Is there any other way to output data on a Window?
回答1:
You can put a Static or an Edit control (Label and a text box) on your window to show the data.
Call one of these during WM_CREATE
:
HWND hWndExample = CreateWindow("STATIC", "Text Goes Here", WS_VISIBLE | WS_CHILD | SS_LEFT, 10,10,100,100, hWnd, NULL, hInstance, NULL);
Or
HWND hWndExample = CreateWindow("EDIT", "Text Goes Here", WS_VISIBLE | WS_CHILD | ES_LEFT, 10,10,100,100, hWnd, NULL, hInstance, NULL);
If you use an Edit
then the user will also be able to scroll, and copy and paste the text.
In both cases, the text can be updated using SetWindowText():
SetWindowText(hWndExample, TEXT("Control string"));
(Curtosy of Daboyzuk)
回答2:
TextOut should work perfectly fine, If this is done in WM_PAINT it should be drawn every time. (including on minimizing and re-sizing)
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
TextOut(hdc, 10, 10, TEXT("Text Out String"),strlen("Text Out String"));
EndPaint(hWnd, &ps);
ReleaseDC(hWnd, hdc);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
You might also be interested in DrawText
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_PAINT:
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
RECT rec;
// SetRect(rect, x ,y ,width, height)
SetRect(&rec,10,10,100,100);
// DrawText(HDC, text, text length, drawing area, parameters "DT_XXX")
DrawText(hdc, TEXT("Text Out String"),strlen("Text Out String"), &rec, DT_TOP|DT_LEFT);
EndPaint(hWnd, &ps);
ReleaseDC(hWnd, hdc);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
Which will draw the text to your window in a given rectangle,
Draw Text will Word Wrap inside of the given rect.
If you want to have your whole window as the draw area you can use GetClientRect(hWnd, &rec);
instead of SetRect(&rec,10,10,100,100);
来源:https://stackoverflow.com/questions/15429541/displaying-string-output-in-a-window-using-c-in-win32-api