This is a collection of useful Windows programming snippets we've used throughout the years on various projects. There are also some useful snippets in the Porting to Microsoft Visual C++ page, although those will be related to cross-platform development.
Windows are everything in Windows, even controls, some of the Win32 API functions to deal with this core component of the operating system are sometimes laughable, so we need to create our own wrappers to make them useful.
Such a simple operation should've been so simple and straightforward, after all it's something that you'll be doing a lot in Windows, but the people that designed the API didn't think about including a little helper to make this task easier.
/** * Gets a window's text property into a newly allocated buffer. No need for * pointer wrangling. * * @warning This function allocates memory that must be free'd by you. * * @param hWnd Handle of the window we want the text from. * * @return Newly allocated buffer with the window's text. */ LPTSTR GetWindowTextAlloc(HWND hWnd) { int iLen; LPTSTR szText; /* Get the length of the text. */ iLen = GetWindowTextLength(hWnd) + 1; /* Allocate the memory to receive the window's text. */ szText = (LPTSTR)malloc(iLen * sizeof(TCHAR)); if (szText == NULL) return NULL; /* Get the text from the window. */ GetWindowText(hWnd, szText, iLen); return szText; }
Dialogs are almost the heart of every Windows application, so there are a lot of repetitive things that we usually want to do with them.
Whenever we are opening a new dialog, commonly, we want it to open in the center of the dialog's parent window. This is so common that Microsoft has even documented it.
HWND hwndOwner; RECT rc, rcDlg, rcOwner; .... case WM_INITDIALOG: // Get the owner window and dialog box rectangles. if ((hwndOwner = GetParent(hwndDlg)) == NULL) { hwndOwner = GetDesktopWindow(); } GetWindowRect(hwndOwner, &rcOwner); GetWindowRect(hwndDlg, &rcDlg); CopyRect(&rc, &rcOwner); // Offset the owner and dialog box rectangles so that right and bottom // values represent the width and height, and then offset the owner again // to discard space taken up by the dialog box. OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); OffsetRect(&rc, -rc.left, -rc.top); OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); // The new position is the sum of half the remaining space and the owner's // original position. SetWindowPos(hwndDlg, HWND_TOP, rcOwner.left + (rc.right / 2), rcOwner.top + (rc.bottom / 2), 0, 0, // Ignores size arguments. SWP_NOSIZE); if (GetDlgCtrlID((HWND) wParam) != ID_ITEMNAME) { SetFocus(GetDlgItem(hwndDlg, ID_ITEMNAME)); return FALSE; } return TRUE;