Displaying String Output in a Window using C (in WIN32 API) - c

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?

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"));
(Courtesy of Daboyzuk)

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);

Related

creating a window with createwindow() when clicking a menu command

I want to create a window with CreateWindow() when clicking on a menu item that will be a child of the main window. I know I can use DialogBox() or CreateDialog() but I want to use CreateWindow(). I'm using this code
resource.rc file
#include "resource.h"
IDM_MENU MENU
{
POPUP "&Help"
{
MENUITEM "&About", IDM_HELP
}
}
About window procedure
LRESULT CALLBACK AboutProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
Main window procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case IDM_HELP:
{
WNDCLASSEX wc;
HWND hDlg;
MSG msg;
SecureZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hIcon = (HICON)GetClassLong(hwnd, GCL_HICON);
wc.hIconSm = (HICON)GetClassLong(hwnd, GCL_HICONSM);
wc.hInstance = GetModuleHandle(0);
wc.lpfnWndProc = AboutProc;
wc.lpszClassName = TEXT("AboutClass");
if(!RegisterClassEx(&wc))
break;
hDlg = CreateWindowEx(0, wc.lpszClassName, TEXT("About"), WS_OVERLAPPEDWINDOW, 0, 0, 300, 200, hwnd, 0, wc.hInstance, 0);
ShowWindow(hDlg, SW_SHOWNORMAL);
while(GetMessage(&msg, 0, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnregisterClass(wc.lpszClassName, wc.hInstance);
}
break;
}
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
Is this a good idea? Can you register more than one class to the same instance? Also, is it a good idea to assign the main window icons to this child window or should I load them each time? Will those icons be deleted when I call UnregisterClass() in IDM_HELP? I have tried this program and everything works and the icons still show in the main window after I close this child window. But I still wonder if it's ok to assign the main window icons to this window since I call UnregisterClass() after the child window closes
There is nothing wrong with using CreateWindow/Ex() instead of CreateDialog()/DialogBox(). And there is nothing wrong with running your own modal message loop, as long as you implement it correctly. For instance, take heed of this warning:
Modality, part 3: The WM_QUIT message
The other important thing about modality is that a WM_QUIT message always breaks the modal loop. Remember this in your own modal loops! If ever you call the PeekMessage function or the GetMessage function and get a WM_QUIT message, you must not only exit your modal loop, but you must also re-generate the WM_QUIT message (via the PostQuitMessage message) so the next outer layer will see the WM_QUIT message and do its cleanup as well. If you fail to propagate the message, the next outer layer will not know that it needs to quit, and the program will seem to "get stuck" in its shutdown code, forcing the user to terminate the process the hard way.
The example you showed is not doing that, so you would need to add it:
ShowWindow(hDlg, SW_SHOWNORMAL);
do
{
BOOL bRet = GetMessage(&msg, 0, 0, 0);
if (bRet > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if (bRet == 0)
PostQuitMessage(msg.wParam); // <-- add this!
break;
}
}
while (1);
UnregisterClass(wc.lpszClassName, wc.hInstance);
However, your modal window should NOT be using WM_QUIT just to break its modal loop, as doing so would exit you entire application! Use a different signal to make your modal loop break when the window is closed. For example:
ShowWindow(hDlg, SW_SHOWNORMAL);
while (IsWindow(hDlg) && (GetMessage(&msg, 0, 0, 0) > 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
LRESULT CALLBACK AboutProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
Also, a modal window is supposed to disable its owner window, and then re-enable it when closed. Your example is not doing that either, so that needs to be added as well:
ShowWindow(hDlg, SW_SHOWNORMAL);
EnableWindow(hwnd, FALSE); // <-- add this
...
LRESULT CALLBACK AboutProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
EnableWindow(GetWindow(hwnd, GW_OWNER), TRUE); // <-- add this
DestroyWindow(hwnd);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
The Old New Thing blog has a whole series of posts on how to work with modal windows.
Modality, part 1: UI-modality vs code-modality
Modality, part 2: Code-modality vs UI-modality
Modality, part 3: The WM_QUIT message
Modality, part 4: The importance of setting the correct owner for modal UI
Modality, part 5: Setting the correct owner for modal UI
Modality, part 6: Interacting with a program that has gone modal
Modality, part 7: A timed MessageBox, the cheap version
Modality, part 8: A timed MessageBox, the better version
Modality, part 9: Setting the correct owner for modal UI, practical exam
The correct order for disabling and enabling windows
Make sure you disable the correct window for modal UI
Update: based on your comment that "No I don't want a modal window", you can ignore everything said above. All of that applies to modal windows only. Since you do not want a modal window, simply remove the secondary loop altogether and let the main message loop handle everything. Also, you do not need to call UnregisterClass(). It will unregister automatically when the process ends. Call RegisterClass() one time, either at program startup, or at least the first time you display the About window. You can use GetClassInfo/Ex() to know whether the class is already registered, or keep track of it yourself. Think of what happens if the user wants to display the About window more than one time during the process's lifetime. So let it re-use an existing class registration each time.
Try this:
LRESULT CALLBACK AboutProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case IDM_HELP:
{
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = GetModuleHandle(0);
wc.lpszClassName = TEXT("AboutClass");
if (!GetClassInfoEx(wc.hInstance, wc.lpszClassName, &wc))
{
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hIcon = (HICON)GetClassLong(hwnd, GCL_HICON);
wc.hIconSm = (HICON)GetClassLong(hwnd, GCL_HICONSM);
wc.lpfnWndProc = AboutProc;
if (!RegisterClassEx(&wc))
break;
}
HWND hDlg = CreateWindowEx(0, wc.lpszClassName, TEXT("About"), WS_OVERLAPPEDWINDOW, 0, 0, 300, 200, hwnd, 0, wc.hInstance, 0);
if (hDlg)
ShowWindow(hDlg, SW_SHOWNORMAL);
}
break;
}
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
Yes, you can use CreateWindow(). You can do anything in your event handler. Using DialogBox() just gives you a modal loop for free (so your main window cannot be interacted with until the dialog box is closed).
Yes, you can register multiple window classes. You are free to register all your window classes in advance; you do not need to call RegisterClass() and UnregisterClass() each time someone clicks your menu item.
I'm not sure if UnregisterClass() frees the various GDI resources allocated to your window class; anyone who knows the answer is free to comment.

WinAPI - dialogs: how does disabled main window flash dialog on mouseclick?

Using WinAPI in C, there are two ways to create a dialog with WinAPI: the more common one is to create a dialog resource in the project's .rc file and then use it with DialogBox(), which automates the creation of a standart dialog. The other way is to use CreateWindowEx with specific parameters so that the created window acts like a dialog.
An example of dialog creation with DialogBox can be seen at winprog.org: http://www.winprog.org/tutorial/dialogs.html
Out of pure interest, I've tried to recreate the dialog created with DialogBox(), using CreateWindowEx. To do this, I simply disabled the main window and then CreateWindowEx'ed the dialog. However, what I got still had one difference from the dialog created with DialogBox: when I click on the disabled main window, a DialogBox-created dialog flashes (most probably with the FlashWindowEx function).
Here's my code for creating a dialog box with CreateWindowEx:
HWND hwndParent;
HINSTANCE ghInstance;
LPCWSTR g_szDialogClassName = L"DialogClass";
void populateDialog(HWND hwnd){
/* Create various dialog controls */
}
LRESULT CALLBACK aboutDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam){
switch(Message){
case WM_CREATE:
populateDialog(hwnd);
return DefWindowProc(hwnd, Message, wParam, lParam);
case WM_COMMAND:
switch(LOWORD(wParam)){
case IDC_CLOSEDLG:
EnableWindow(hwndParent, TRUE);
DestroyWindow(hwnd);
UnregisterClass(g_szDialogClassName, ghInstance);
break;
}
break;
case WM_CLOSE:
EnableWindow(hwndParent, TRUE);
DestroyWindow(hwnd);
UnregisterClass(g_szDialogClassName, ghInstance);
break;
default:
return DefWindowProc(hwnd, Message, wParam, lParam);
}
return DefWindowProc(hwnd, Message, wParam, lParam);
}
int createDialogBox(HWND hwnd, HINSTANCE hInstance){
if (registerClass(hInstance, g_szDialogClassName, (WNDPROC)aboutDlgProc) == 0){
MessageBoxA(NULL, "Dialog Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}
EnableWindow(hwnd, FALSE);
CreateWindowEx(WS_EX_DLGMODALFRAME | WS_EX_TOPMOST | WS_EX_TOOLWINDOW, g_szDialogClassName, L"About", WS_VISIBLE | WS_CAPTION | WS_POPUP | WS_SYSMENU, 100, 100, 450, 150, NULL, NULL, hInstance, NULL);
hwndParent = hwnd;
}
Now I am very interested in how is this done inside DialogBox()? How can a disabled window recieve mouse input? Or maybe it wasn't disabled by standart means (by something different than EnableWindow(hwnd, FALSE))? Or is it impossible to reproduce this effect with normal WinAPI calls?
The problem with your code is that you created the window un-owned. Specify the main window as the owner when you call CreateWindowEx.

Not able to read value from EDIT box (windows programming and C)

I need help with this code. I need to set the focus to a edit button and read the value entered in the edit box and move it to a variable for further processing. This code creates a text prompt with TextOut() which says " Enter the value of mass:" and an editbox with an IDC_EDIT_MASS and hEditMASS next to it.
I am not able to read the value from edit box into variable mass.
And the code is as follows *
#define IDC_EDIT_MASS 103 // Edit box identifier
RESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM
lParam)
{
HWND hEditMASS;
HDC hDC;
PAINTSTRUCT Ps;
HFONT font;
float mass;
char msgMASS[]="Enter the value of mass:";
switch (message) /* handle the messages */
{
case WM_CREATE :
hEditMASS=CreateWindowEx(WS_EX_CLIENTEDGE, “EDIT",
"", WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL,
550,
200,
200,
20,
hwnd,
(HMENU)IDC_EDIT_MASS,
GetModuleHandle(NULL),
NULL);
Break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_EDIT_MASS:
SendMessage(hEditMASS,WM_GETTEXT, sizeof(buffer)/sizeof(buffer[0]),
reinterpret_cast<LPARAM>(buffer));
int ctxtlen=GetWindowTextlength(GetDlgItem(hwnd, IDC_EDIT_MASS));
GetWindowText(GetDlgItem(hwnd, IDC_EDIT_MASS), buffer,(cTxtLen + 1);
mass=atoi(buffer);
MessageBox(NULL,buffer,"Information",MB_ICONINFORMATION);
break;
}
Break;
case WM_SETFOCUS :
SetFocus (hwnd) ;
break;
case WM_PAINT:
hDC = BeginPaint(hwnd, &Ps);
//inputs prompts ...
TextOut(hDC,300,200,msgMASS,sizeof(msgMASS));
EndPaint(hwnd, &Ps);
break;
case WM_DESTROY:
PostQuitMessage (0); /* send a WM_QUIT to the message queue */
break;
default: /* for messages that we don't deal with */
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
hEditMASS is an local, automatic-storage-duration variable. You set it when the message is WM_CREATE. However, you then access it when the message is WM_COMMAND. Automatic-storage-duration variables do not retain their value between calls. In order for it to retain its value, you must either make it global or make it static, e.g.:
static HWND hEditMASS;
Keep in mind that you'll probably only be able to use your window procedure for one window now, since creating any other window with the same window procedure will end up using the same hEditMASS variable, and when you next try to access hEditMASS, it will point to the edit control in the most-recently-created window with that window procedure.

Creating and using fonts / avoiding memory leaks in windows GDI

I'm trying to get to the bottom of a memory leak in an application written in C and running on Windows CE 6.0. I suspect that the issue MAY be related to the handling of the paint event of the window. In pseudo code it looks like this.
LRESULT CALLBACK HandlePaint(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
hdc = BeginPaint (hWnd, &ps);
HFONT logfont;
FONTINFO font1, font2;
memset(&logfont, 0, sizeof(LOGFONT));
//set font options for font1.
font1 = CreateFontIndirect(&logfont);
memset(&logfont, 0, sizeof(LOGFONT));
//set font options for font2.
font2 = CreateFontIndirect(&logfont);
for(int i = 0; i <= SOME_NUMBER; i++)
{
DrawStuff(hdc, font1);
DrawStuff(hdc, font2);
}
EndPaint (hWnd, &ps);
}
INT DrawStuff(HDC hdc, HFONT font)
{
HPEN pen = CreatePen(PS_SOLID, borderWidth, bordercolor);
HBRUSH brush = CreateSolidBrush(backcolor);
SelectObject (hdc, pen);
SelectObject (hdc, brush);
SelectObject(hdc, font);
SetTextColor (hdc, forecolor);
SetBkColor (hdc, backcolor);
DrawText (hdc, pChar, wcslen(pChar), prect, DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX);
DeleteObject(font);
DeleteObject(brush);
DeleteObject(pen);
}
I've noticed in the examples I've seen for windows graphics that there seems to be a pattern for most grapics objects of:
HBRUSH brush = CreateBrush();
SelectObject(hdc, brush);
// use brush
DeleteObject(brush);
However, as you can see in the example above with the fonts, each font is being created once, and then Selected/Deleted multiple times. I'm not sure what the implications are of doing that. Would there be a reason to suspect a memory leak here?
Thanks!
I agree with #pmg's comment that the creator of the Form should be the destroyer of the font, not the DrawStuff callee.
Also bear in mind that SelectObject returns the original item in the DC and you should always return that object when you're done, e.g.:
HPEN newPen = CreatePen(...);
HPEN oldPen = SelectObject(hdc, newPen);
// do stuff
// clean up
SelectObject(hdc, oldPen); // <-- note this line
DeleteObject(newPen);

Change height of COMBOBOX

How can I change the height of a COMBOBOX control created with a resource-definition at runtime, so that I can insert new strings in the combobox? The string insertion code is working but only if I set a fixed height for the combobox in the resource-definition (e.g. 28 units). But this is not convenient, because the number of strings is dynamic.
I know that I can create the dialog at runtime, but then I can't use dialog units, and resources are much more efficient...
Here are simplified versions of my code.
Resource file:
IDD_SETTINGS DIALOG 0, 0, 100, 100
BEGIN
COMBOBOX IDC_COMBO, 0, 0, 100, 14, CBS_DROPDOWNLIST
END
Window procedure for main window and dialog:
BOOL CALLBACK WndProcSettings(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_INITDIALOG:
//...
break;
default:
return FALSE;
}
return TRUE;
}
LRESULT CALLBACK WndProcMain(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_SETTINGS:
DialogBox(hInstance, MAKEINTRESOURCE(IDD_SETTINGS), hWnd, WndProcSettings);
break;
}
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return(0L);
}
I assume you are referring to the height of the dropdown portion of the combobox.
You can still work with Dialog Units, take a look at GetDialogBaseUnits which will return the number of pixels per dialog unit. If you are working with a non-system font the following KB article details the calculations - How To Calculate Dialog Base Units with Non-System-Based Font.
You can programatically change the size of the combobox by using SetWindowPos.
In the meantime, I found a solution. Here is what I'm using now. I set the height for the combobox in the resource file to 14 DLU's (height of one item), so that the new height is calculated correctly. Using GetClientRect I get this height, and convert it to pixels with MapDialogRect.
HWND hCtl;
RECT rect;
hCtl = GetDlgItem(hWnd, IDC_COMBO);
GetClientRect(hCtl, &rect);
MapDialogRect(hCtl, &rect);
SetWindowPos(hCtl, 0, 0, 0, rect.right, (n_choices + 1) * rect.bottom, SWP_NOMOVE);

Resources