+ -
当前位置:首页 → 问答吧 → 怎样在多线程中创建控件?

怎样在多线程中创建控件?

时间:2011-12-07

来源:互联网

问题:在 vc 中创建 Win32 Application,通过 SDK 创建窗口并添加控件,这些代码是比较容易的。在这个代码的基础上,将创建控件的代码放到另一个线程中却不能实现。

以下代码创建了一个文本框和一个按钮,按钮就是在原线程中创建的,没有问题;文本框是在另一个线程中创建的,不能显示。请问该怎样做?

C/C++ code

#include <windows.h>

HINSTANCE g_hInstance;
HWND hEdit, hButton;
HWND g_hwnd;


DWORD WINAPI ThreadFunc(LPVOID para)
{
    hEdit = CreateWindow("Edit","Edit",WS_BORDER | WS_VISIBLE | WS_CHILD,
        10,10,50,20,g_hwnd,NULL,g_hInstance,NULL);
    return 0;
}


LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    g_hwnd = hwnd;

    switch (uMsg)
    {
        case WM_CREATE:
            hButton = CreateWindow("Button","Button",WS_VISIBLE | WS_CHILD,
                15,30,55,20,g_hwnd,NULL,g_hInstance,NULL);
            CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc, 0, 0, 0);
            break;

        case WM_DESTROY:
            PostQuitMessage(0);
            break;

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


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    g_hInstance = hInstance;

    WNDCLASS ws;
    ws.cbClsExtra=0;
    ws.cbWndExtra=0;
    ws.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
    ws.hCursor=LoadCursor(NULL,IDC_ARROW);
    ws.hIcon=LoadIcon(NULL,IDI_APPLICATION);
    ws.hInstance=hInstance;
    ws.lpszClassName="学习";
    ws.lpszMenuName=NULL;
    ws.style=CS_HREDRAW|CS_VREDRAW;
    ws.lpfnWndProc=WindowProc;
    RegisterClass(&ws);
    
    HWND hwnd=CreateWindow("学习","hello word!",WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX,150,10,200,100,0,0,hInstance,0);
    ShowWindow(hwnd,SW_NORMAL);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg,NULL,0,0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}




作者: wumingcn   发布时间: 2011-12-07

在一个应用程序中,原则上只有一个线程用于界面工作
所有创建销毁控件都放在一个线程中,方便管理
你创建的编辑框控件肯定成功了,你可以跟踪看看返回值

作者: sky101010ws   发布时间: 2011-12-07

user32 中的对象只属于创建她的那个线程.

你不要这么做.

作者: dongyuechushi   发布时间: 2011-12-07