WinAPI FindWindow

1.4k views Asked by At

I am building a win32 application in visual studio 2012. I have 4 disabled buttons created with the following code:

HWND hWndButton=CreateWindowEx(NULL, 
        L"BUTTON",
        L"APP1",
        WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON|WS_DISABLED|BS_ICON,
        40,
        40,
        180,
        140,
        hWnd,
        (HMENU)IDC_BUTTON1,
        GetModuleHandle(NULL),
        NULL);

What I want to do is to enable the buttons as the application runs. I tried to use findwindow to find and enable the first button but it doesn't find it. My code is:

HWND hwB1 = FindWindow(L"BUTTON",L"APP1");
if (hwB1 !=0)   MessageBox(NULL,L"FOUND",L"Button Found",MB_OK);
EnableWindow(hwB1,true);

Am I doing something wrong? Thank you in advance.

2

There are 2 answers

0
Jonathan Potter On BEST ANSWER

FindWindow() finds top-level windows, not child windows.

If you really do want to look up a child window by name, you can use the FindWindowEx() function, but using the ID is usually more efficient.

The function that does this is GetDlgItem(). This looks up child windows by their ID, which you provide when you create them.

HWND hwB1 = GetDlgItem(hWnd, IDC_BUTTON1);

hWnd is the parent window, and IDC_BUTTON1 is the ID.

Another alternative is to simply store the window handle that's returned when you create the child window - hWndButton in your code example - and then you don't need to look it up at all.

1
William Chan On

Use FindWindowEx(),

HWND hwB1=FindWindowEx(hWnd/*Parent window*/,
                       hWndButton/*Child window*/,
                       "BUTTON"/*Class of the child window*/,
                       "APP1"/*Title of the child window*/);

This is a better method when the control ID is unknown.