C ++ runs a function in async, not block ui

I have a small app that checks the dotnet framework, if not installed it will install it

Now when the app starts, I want to pop up a gif image with something like loading and check the framework in the background and install.

catch here is that it can't have any preconditions to run the app

that's what i have so far

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                  _In_opt_ HINSTANCE hPrevInstance,
                  _In_ LPWSTR lpCmdLine,
                  _In_ int nCmdShow)
{
       int exitCode = -1;
       showPic(hInstance);
       MessageBox(0L, L"Dotnet will installed", L"Alert", 0);
       auto fut = std::async(std::launch::async, DoWork, hInstance, lpCmdLine);
       fut.wait();
       exitCode = fut.get();
       return exitCode;
}

      

showPic ()

void showPic(HINSTANCE hInstance)
{
    loadImage(hInstance);
    // create window
    wnd = createWindow(hInstance);
    SetWindowLong(wnd, GWL_STYLE, 0);
    ShowWindow(wnd, SW_SHOW);
}

      

loadImage (HINSTANCE hInstance)

void loadImage(HINSTANCE hInstance)
{
    imageDC = CreateCompatibleDC(NULL);
    imageBmp = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_BITMAP1));
    imageBmpOld = (HBITMAP)SelectObject(imageDC, imageBmp);
}

      

Now what happens is that if I do not show the message then the image is not loaded in the window and still the window goes into unresponsive mode and I could not get it to work with gif, only with bmp images any help is determined

now since i'm waiting for fut it is obvious that it will block ui until it gets a value what is the workaround for this

+3


source to share


1 answer


It should be simple. Create a window, show it, call the thread, go to the main message loop. When the thread is done, it will destroy the window.



struct T_data {
    HWND hWnd;
    HINSTANCE hInstance;
    LPTSTR cmdline;
    int exitCode;
};

DWORD WINAPI taking_too_long(LPVOID p) {
    Sleep(2000); //wait at least 2 seconds!
    T_data* data = reinterpret_cast<T_data*>(p);
    auto fut = std::async(std::launch::async, DoWork, data->hInstance, data->lpCmdLine);
    fut.wait();
    data->exitCode = fut.get();
    //make sure the window handles IDM_EXIT to close itself
    PostMessage(data->hWnd, WM_COMMAND, IDM_EXIT, 0);
}

int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR lpCmdLine, int) {
    T_data data;
    data.exitCode = -1;
    data.hWnd = hWnd;
    data.hInstance = hInstance;
    data.cmdline = lpCmdLine;

    data.hWnd = showPic(hInstance);

    CreateThread(NULL, 0, taking_too_long, &data, 0, NULL);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return data.exitCode;
}

      

+4


source







All Articles