窗口线程是由消息线程发展出来的

来源:互联网 发布:ubuntu下制作启动u盘 编辑:程序博客网 时间:2024/05/20 13:14
 

开始以为创建的子线程没有执行,后来加入延时之后才发现本来也是执行了的。刚开始看多线程,跟大家分享下,还望多多指教,呵呵~

#include <Windows.h>
#include <iostream>

using namespace std;

LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
DWORD WINAPI MyThread(void *p);

int APIENTRY WinMain(HINSTANCE hInstance,
      HINSTANCE hPreInstance,
      LPSTR lpCmdLine,
      int nCmdShow)
{
 WNDCLASSEX wndclass;
 static char szAppName[] = "Hello Everyone";
 wndclass.cbSize = sizeof(wndclass);
 wndclass.style = CS_HREDRAW|CS_VREDRAW;
 wndclass.lpfnWndProc = WndProc;
 wndclass.cbClsExtra =0;
 wndclass.cbWndExtra = 0;
 wndclass.hInstance = hInstance;
 wndclass.hIcon = LoadIcon(hInstance,IDI_APPLICATION);
 wndclass.hCursor = LoadCursor(NULL,IDC_ARROW);
 wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
 wndclass.lpszMenuName = NULL;
 wndclass.lpszClassName = szAppName;
 wndclass.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
 
 RegisterClassEx(&wndclass);

 DWORD dw;
 HANDLE handle;
 handle = CreateThread(NULL,0,MyThread,(void *)&wndclass,0,&dw);

 //创建好线程之后就会执行线程函数,此时先暂停一下
 //之后的三秒连续向这个线程发送WM_PAINT消息,这个消息会进入MyThread消息线程的消息队列,线程函数中有消息循环
 //会从线程消息队列中取出这个消息,之后根据hWnd发送给对应的窗体,随后跟窗口类绑定的消息响应函数会对应地处理
 //这个消息
 //随后向线程发送WM_QUIT消息,具体执行流程如上所示。
 Sleep(1000);
 system("pause");
 int i = 3;
 while (i >= 0)
 {
  PostThreadMessage(dw,WM_PAINT,0,0);
  Sleep(1000);
  i--;
 }
 PostThreadMessage(dw,WM_QUIT,0,0);
 CloseHandle(handle);

 //延时三秒之后,这次只是调用函数而已,跟创建子线程无关。
 Sleep(3000);
 MyThread(&wndclass);

 return 0;
}

DWORD WINAPI MyThread(void *p)
{
 HWND hWnd;
 MSG msg;
 WNDCLASSEX *pw = (WNDCLASSEX*)p;

 hWnd = CreateWindow(
  pw->lpszClassName,
  "Thread Window",
  WS_OVERLAPPEDWINDOW,
  CW_USEDEFAULT,
  CW_USEDEFAULT,
  CW_USEDEFAULT,
  CW_USEDEFAULT,
  NULL,
  NULL,
  pw->hInstance,
  NULL);

 //cout << "Come Here" << endl;

 ShowWindow(hWnd,SW_SHOWNORMAL);
 UpdateWindow(hWnd);

 while (GetMessage(&msg,NULL,0,0))
 {
  //PostMessage(hWnd,msg.message,0,0);
  TranslateMessage(&msg);
  DispatchMessage(&msg);
 }

 return msg.message;
}

 

LRESULT CALLBACK WndProc(HWND hWnd,
       UINT iMessage,
       WPARAM wParam,
       LPARAM lParam)
{
 HDC hdc;
 PAINTSTRUCT ps;
 RECT rect;

 switch (iMessage)
 {
 case WM_PAINT:
  hdc = BeginPaint(hWnd,&ps);
  GetClientRect(hWnd,&rect);
  DrawText(hdc,"Thread created", -1, &rect, DT_SINGLELINE|DT_CENTER|DT_VCENTER);
  EndPaint(hWnd,&ps);
  return 0;
 case WM_DESTROY:
  PostQuitMessage(0);
  break;
 default:
  return DefWindowProc(hWnd,iMessage,wParam,lParam);
 }
 return (0L);
}

原创粉丝点击