Monday, December 23, 2013

To close child windows, but not parent window

If an application wants to close all its child windows but not parent windows, the following code can help. In the parent window code:

HWND hwnd1 = FindWindowW(L"MyWindowClass2", L"Direct2D Video Window2");  // classname, and then windowname

PostMessage(hwnd1, WM_CLOSE, 0, NULL);


Then, in the child window code, need to implement the message handler to respond WM_CLOSE.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
       switch (message)
       {
              case WM_CLOSE:
                     DestroyWindow(hWnd);
                     break;
              case WM_DESTROY:
                     PostQuitMessage(0);
                     break;
              default:
                     return DefWindowProc(hWnd, message, wParam, lParam);
       }
       return 0;
}

For clasname and window name, these can be defined when manually creating a child window using code, as follows:

ATOM CMyWindowExample::MyRegisterClass()
{
       WNDCLASSEX wcex;

       wcex.cbSize = sizeof(WNDCLASSEX);

       wcex.style                 = CS_HREDRAW | CS_VREDRAW;
       wcex.lpfnWndProc     = WndProc;
       wcex.cbClsExtra            = 0;
       wcex.cbWndExtra            = 0;
       wcex.hInstance             = GetModuleHandle(NULL);
       wcex.hIcon                 = LoadIcon(NULL, IDI_APPLICATION);
       wcex.hCursor         = LoadCursor(NULL, IDC_ARROW);
       wcex.hbrBackground   = NULL;
       wcex.lpszMenuName    = NULL;
       wcex.lpszClassName   = L"MyWindowClass1";
       wcex.hIconSm         = LoadIcon(NULL, IDI_APPLICATION);

       return RegisterClassEx(&wcex);
}


HWND CMyWindowExample::InitInstance(LPCWSTR windowName, int width, int height)
{
       int x = ::GetSystemMetrics(SM_CXSCREEN) / 2 - width / 2;
       int y = ::GetSystemMetrics(SM_CYSCREEN) / 2 - height / 2;

      
       m_hWnd = CreateWindow(L"MyWindowClass1", windowName, WS_OVERLAPPEDWINDOW, x, y, width, height, NULL, NULL, NULL, NULL);

        
    return m_hWnd;
}

0 Comments:

Post a Comment

<< Home