Like many developers who write code in their free time, I have an overwhelming backlog of side projects. A lot of these projects don’t get finished for the usual variety of reasons: lack of time, loss of interest, another side projects comes up, and so on. As I searched through the folders of these projects, I realized that while I might not be able to complete them now or in the future, that there are certain portions of them that I can carve out and post about. These snippets will typically be short code blocks that I had written to solve a rather particular problem at the time.
The code snippet covered here will be a function I wrote called FindWindowLike. Interestingly enough, while Googling this, there appears to be an MSDN article from 1997 which lists a VB6 function that does the same thing. The one posted here is implemented much differently than that horrible mess though. The purpose of this function is to get a handle to a window while knowing only part of its title. This was useful when I was trying to get a window handle which changed on every instance of the program — for example the process id was part of the title. The code is very straightforward and uses EnumWindows to enumerate all windows on the desktop and perform a substring match.
typedef struct { const TCHAR * const pPartialTitle; const bool bCaseSentitive; HWND hFoundHandle; } WindowInformation; BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { //Read up to 255 characters of window title TCHAR strWindowTitle[255] = { 0 }; auto success = GetWindowText(hWnd, strWindowTitle, sizeof(strWindowTitle)); if (success > 0) { WindowInformation *pWindowInfo = (WindowInformation *)lParam; auto isFound = pWindowInfo->bCaseSentitive ? StrStr(strWindowTitle, pWindowInfo->pPartialTitle) : StrStrI(strWindowTitle, pWindowInfo->pPartialTitle); if (isFound) { pWindowInfo->hFoundHandle = hWnd; return FALSE; } } return TRUE; } const HWND FindWindowLike(const TCHAR * const pPartialTitle, const bool bCaseSensitive = true) { WindowInformation windowInfo = { pPartialTitle, bCaseSensitive, nullptr }; (void)EnumWindows(EnumWindowsProc, (LPARAM)&windowInfo); if (windowInfo.hFoundHandle == nullptr) { fprintf(stderr, "Could not find window.\n"); } return windowInfo.hFoundHandle; } |
The sample code is hosted on GitHub here.