【问题标题】:How to create a new window in a speparate thread?如何在单独的线程中创建新窗口?
【发布时间】:2021-09-03 00:00:25
【问题描述】:

我想在新线程中创建一个新的 POPUP 样式窗口。这是我到目前为止的代码。

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
#include <tchar.h>
#include <thread>
#include <string>

#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
using namespace std;

const wchar_t g_szClassName[] = L"Skeleton";
const wchar_t g_szChildClassName[] = L"Child";

wchar_t msgbuf[100];
char msgbuf_ansi[100];
WNDCLASSEX wc;

struct MyStruct
{
    WNDCLASSEX wc;
    HWND hWnd;
    HINSTANCE hInst;
    int nCmdShow;
};

MyStruct g_myStruct;
LRESULT CALLBACK WndProcChild(HWND, UINT, WPARAM, LPARAM);

void Example_DrawImage9(HDC hdc) {
    Graphics graphics(hdc);
    Image image(L"C:/Users/Darek/Fallout2_older/data/art/iface/armor_info.bmp");
    graphics.DrawImage(&image, 0, 0);
}

int task1(MyStruct myStruct)
{
    sprintf_s(msgbuf_ansi, ("thread\n"));
    OutputDebugStringA(msgbuf_ansi);

    HWND hwnd_child;

    myStruct.wc.lpfnWndProc = WndProcChild;
    myStruct.wc.lpszClassName = g_szChildClassName;

    if (!RegisterClassEx(&myStruct.wc)) {
        MessageBox(NULL, L"thread - Window Registration Failed!", L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd_child = CreateWindowEx(0, g_szChildClassName, L"Child", WS_POPUP | WS_BORDER, 200, 0, 190, 110, myStruct.hWnd, 0, myStruct.hInst, 0);

    swprintf_s(msgbuf, _T("THREAD - CHILD -  hwnd: %02X\n"), (int)hwnd_child);
    OutputDebugString(msgbuf);

    if (hwnd_child == NULL) {
        MessageBox(NULL, L"thread - Window Creation Failed!", L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    SetWindowLong(hwnd_child, GWL_EXSTYLE, GetWindowLong(hwnd_child, GWL_EXSTYLE) | WS_EX_LAYERED);
    SetLayeredWindowAttributes(hwnd_child, 0, 128, LWA_ALPHA);
    ShowWindow(hwnd_child, myStruct.nCmdShow);
    UpdateWindow(hwnd_child);
}
thread t1;
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg) {

        //case WM_KEYDOWN:

    case WM_CLOSE:
        swprintf_s(msgbuf, _T("WM_CLOSE - PARENT \n"));
        OutputDebugString(msgbuf);
        if (MessageBox(hwnd, L"Really quit?", L"My application", MB_OKCANCEL) == IDOK)
        {
            DestroyWindow(hwnd);
        }
        return 0;

    case WM_DESTROY:
        swprintf_s(msgbuf, _T("WM_DESTROY - PARENT \n"));
        OutputDebugString(msgbuf);
        PostQuitMessage(0);
        return 0;

    case WM_CREATE: {
        swprintf_s(msgbuf, _T("WM_CREATE - PARENT \n"));
        OutputDebugString(msgbuf);
        thread t1(task1, g_myStruct);
        t1.join();
        return 0;
    }

    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}
int g_fMouseTracking = FALSE;
LRESULT CALLBACK WndProcChild(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg) {
    case WM_PAINT:
        HDC hdc;
        PAINTSTRUCT ps;

        swprintf_s(msgbuf, _T("WM_PAINT - CHILD -  hwnd: %02X\n"), (int)hwnd);
        OutputDebugString(msgbuf);

        hdc = BeginPaint(hwnd, &ps);
        Example_DrawImage9(hdc);
        EndPaint(hwnd, &ps);

        return 0;

        //case WM_KEYDOWN:

    case WM_CREATE: {
        swprintf_s(msgbuf, _T("WM_CREATE - CHILD \n"));
        OutputDebugString(msgbuf);
        return 0;
    }

    case WM_MOUSEMOVE:
        swprintf_s(msgbuf, _T("WM_MOUSEMOVE - CHILD -  hwnd: %02X\n"), (int)hwnd);
        OutputDebugString(msgbuf);

        if (!g_fMouseTracking)
        {
            // start tracking if we aren't already
            TRACKMOUSEEVENT tme = {};
            tme.cbSize = sizeof(TRACKMOUSEEVENT);
            tme.dwFlags = TME_HOVER | TME_LEAVE;
            tme.hwndTrack = hwnd;
            tme.dwHoverTime = HOVER_DEFAULT;

            g_fMouseTracking = TrackMouseEvent(&tme);
        }

        return 0;

    case WM_MOUSELEAVE:
        swprintf_s(msgbuf, _T("WM_MOUSELEAVE  - CHILD -  hwnd: %02X\n"), (int)hwnd);
        OutputDebugString(msgbuf);

        g_fMouseTracking = FALSE; // tracking now canceled

        return 0;

    case WM_CLOSE:
        swprintf_s(msgbuf, _T("WM_CLOSE - CHILD \n"));
        OutputDebugString(msgbuf);
        /*if (MessageBox(hwnd, L"Really quit?", L"My application", MB_OKCANCEL) == IDOK)
        {
            DestroyWindow(hwnd);
        }*/
        return 0;

    case WM_DESTROY:
        swprintf_s(msgbuf, _T("WM_DESTROY - CHILD \n"));
        OutputDebugString(msgbuf);
        PostQuitMessage(0);
        return 0;

    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    //WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    ULONG_PTR token;
    GdiplusStartupInput input = { 0 };
    input.GdiplusVersion = 1;
    GdiplusStartup(&token, &input, NULL);

    //Step 1: Registering the Window Class
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    g_myStruct.wc = wc;
    
    g_myStruct.hInst = hInstance;
    g_myStruct.nCmdShow = nCmdShow;

    if (!RegisterClassEx(&wc)) {
        MessageBox(NULL, L"Window Registration Failed!", L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(0, g_szClassName, L"Skeleton", WS_BORDER, 0, 0, 190, 110, 0, 0, hInstance, 0);
    g_myStruct.hWnd = hwnd;
    if (hwnd == NULL) {
        MessageBox(NULL, L"Parent Window Creation Failed!", L"Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    swprintf_s(msgbuf, _T("MAIN - PARENT -  hwnd: %02X\n"), (int)hwnd);
    OutputDebugString(msgbuf);

    SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
    SetLayeredWindowAttributes(hwnd, 0, 128, LWA_ALPHA);
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&Msg, NULL, 0, 0) > 0) {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    return Msg.wParam;
}

问题在于,正如我调试的那样,确实创建了子窗口,但在 WndProcChild 返回时会自动/神奇地销毁。

如何更正代码以使其按预期运行(子窗口保持打开状态直到主窗口未被破坏)?

【问题讨论】:

  • 我不确定您是否真的想要拥有多线程 GUI。通常,当人们完全接受后果时,他们会意识到他们真正想要的是单个 GUI 线程。
  • 同意@DavidHeffernan。用户没那么快。单个内核的速度足以处理所有鼠标点击和键盘按下。只是不要让 UI 线程自己完成所有工作以响应这些用户操作。
  • @DavidHefferman 可能有单独的消息泵来控制并行进程(nmessage 泵不仅控制 gui,还控制 abd 线程系统交互或 interprocess )而不会导致进程或 gui 锁定。但我宁愿使用一些确实具有此类功能的框架,而不是自己滚动它,尤其是不热衷于阅读他们网站上的官方文档(这个问题在线程一章中逐字回答)

标签: c++ windows winapi visual-c++


【解决方案1】:

线程拥有它创建的窗口和它的消息队列,因此必须提供一个事件循环。它被销毁是因为在 Win API 中,所有权是以 RAII 方式处理的——当所有者不复存在时,获取的对象也是如此。

【讨论】:

  • Windows API 中的资源管理明确手动。不知道你从哪里得到这个想法是自动的。
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 2013-05-22
  • 1970-01-01
相关资源
最近更新 更多