Notify CDialog-Window when selecting another window

1k Views Asked by At

I got a dialog-based MFC-Tool that is supposed to show the title of a window of another application in a messagebox when i click on it. My Problem is that the WM_KILLFOCUS doesn't work here. Maybe I'm doing it wrong. I do the following:

BEGIN_MESSAGE_MAP(CMyDlg, CDialog)
    ON_WM_KILLFOCUS()
END_MESSAGE_MAP()

...
...

void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
    CDialog::OnKillFocus(pNewWnd);
    if(m_bSelectorModeActive)
    {
        HWND hwnd(GetForegroundWindow());
        TCHAR buf[512];
        ::GetWindowText(hwnd, buf, 512);
        MessageBox(buf);
    }
}

Any idea what's wrong?

3

There are 3 best solutions below

0
On

This is my guess

Replace HWND hwnd(GetForegroundWindow()); with GetActiveWindow(void) .

0
On

The code you've shown shouldn't even compile. The GetForegroundWindow function provided by MFC doesn't return an HWND, so you can't initialize the hwnd variable using its return value.

If you want to get an HWND, you need to call GetForegroundWindow from the Windows API by escaping the call with ::, just like you did for GetWindowText. So simply rewrite your code as follows:

void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
    CDialog::OnKillFocus(pNewWnd);
    if(m_bSelectorModeActive)
    {
        HWND hwnd(::GetForegroundWindow());
        TCHAR buf[512];
        ::GetWindowText(hwnd, buf, 512);
        MessageBox(buf);
    }
}

Beyond that, in looking at your code, one wonders that you seem to be ignoring the object-orientation MFC so humbly attempts to bring to the Windows API. You shouldn't need to work directly with window handles. And one could argue that the most compelling reason to use MFC is its CString class. There's no reason you should have to deal with an array of TCHARs anymore. I might write this instead:

void CMyDlg::OnKillFocus( CWnd* pNewWnd )
{
    CDialog::OnKillFocus(pNewWnd);
    if(m_bSelectorModeActive)
    {
        CWnd* pForeWnd = GetForegroundWindow();
        CString windowText;
        pForeWnd->GetWindowText(windowText);
        MessageBox(windowText);
    }
}
1
On

I solved it, thanks for your efforts.

Yes, i do use CStrings, this was just a little example of a bit more complex thing i do. My problem was not the function itself but the event WM_KILLFOCUS that didn't seem to work. Maybe I was not clear enough here, sorry.

WM_ACTIVATE does what i need. It notifies my dialog when the focus is set and/or lost.