0

I want to destroy a child window when user click somewhere outside its window. I tried to use SetCapture() to detect mouse click. Here is the code:

HWND textbox;

//IN case WM_CREATE:
 CreateWindowEx(NULL, L"BUTTON", L"button!",
        WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 10, 10, 150, 40, hwnd,
        (HMENU)IDC_TEXTBOX, NULL, NULL);

 textbox = CreateWindowEx(
        NULL, L"EDIT", NULL,
        WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_BORDER,
        100, 100, 300, 200, hwnd, (HMENU)ID_TEXTBOX, NULL, NULL
    );
 SetWindowText(textbox, L"the initial text");

//IN CASE WM_ONLBUTTONDOWN:
  if (textbox != NULL) {
        if (SetCapture(textbox) == NULL) {
            ReleaseCapture();
            DestroyWindow(textbox);
            textbox = NULL;
        }
    }

The window did get destroyed when i clicked outside its region. HOWEVER, when i click the button it didn't get destroyed as i expected. I want the child window to get destroyed when user clicks WHEREVER outside its window. Why did my code fail? And how do i do this right?

EDIT: Here is a screenshot to make things clear. The window only have an edit window with initial text and a button. As mentioned above, the child window disappears when i click outside its window but when i click the button (which is also outside window), the edit window remains. enter image description here

Halsey
  • 119
  • 1
  • 8
  • Hard to say what's wrong, since we cannot see a [mcve]. Though you probably want to `SetCapture` right after creation, and handle `WM_CAPTURECHANGED`. – IInspectable Jun 10 '21 at 16:13

1 Answers1

0

According to this thread, I find the EN_KILLFOCUS notification which will work for you in the Edit Control Document.

YangXiaoPo-MSFT
  • 1,589
  • 1
  • 4
  • 22
  • You receive an `EN_KILLFOCUS` when the user navigates away using the keyboard. The question is specifically asking for mouse input. Capturing mouse input and destroying the window on `WM_CAPTURECHANGED` accomplished that. – IInspectable Jun 11 '21 at 07:42