WM_QUIT的困扰

来源:互联网 发布:摄像头录像软件 免费 编辑:程序博客网 时间:2024/05/17 07:34
下面的程序是根据《WIN32多线程程序设计》修改得到的:#include "stdafx.h"#include #include #include #include #include #include #include #include #define MY_MSG WM_USER+100HANDLE hStartEvent;void CALLBACK TimerFunc( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime ){UNREFERENCED_PARAMETER( hwnd );UNREFERENCED_PARAMETER( uMsg );PostThreadMessage( GetCurrentThreadId(), WM_QUIT, 0, 0 );}unsigned __stdcall fun( void *param ){printf( "thread fun start/n" );MSG msg;PeekMessage( &msg, NULL, WM_USER, WM_USER, PM_NOREMOVE );if( !SetEvent( hStartEvent ) ){printf( "set start event failed,errno:%d/n", ::GetLastError() );return 1;}SetTimer( NULL, NULL, 2000, (TIMERPROC)TimerFunc );bool bRet = false;while ( ( bRet = GetMessage( &msg, 0, 0, 0 ) ) != false ){if ( bRet == -1 ){// handle the error and possibly exit }else{// process msg here switch( msg.message ){case MY_MSG:{char * pInfo = ( char * )msg.wParam;printf( "recv %s/n", pInfo );delete[] pInfo;}break;default:{if ( msg.message == WM_TIMER ){printf( "message id = %3d, is WM_TIMER /n", msg.message );}DispatchMessage( &msg );}break;}}}if ( msg.message == WM_QUIT ){printf( "message id = %3d, is WM_QUIT /n", msg.message );printf( "bRet = %d /n", bRet );}return 0;}int main(){const int MAX_INFO_SIZE = 20;HANDLE hThread;unsigned nThreadID;hStartEvent = ::CreateEvent( 0, FALSE, FALSE, 0 );if( hStartEvent == 0 ){printf( "create start event failed,errno:%d/n", ::GetLastError() );return 1;}hThread = ( HANDLE )_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID );if(hThread == 0){printf( "start thread failed,errno:%d/n", ::GetLastError() );CloseHandle( hStartEvent );return 1;}::WaitForSingleObject( hStartEvent, INFINITE );CloseHandle( hStartEvent );int count = 0;char* pInfo = new char[MAX_INFO_SIZE];sprintf( pInfo, "msg_%d", ++count );if( !PostThreadMessage( nThreadID, MY_MSG, (WPARAM)pInfo, 0 ) ){printf( "post message failed,errno:%d/n", ::GetLastError() );delete[] pInfo;}WaitForSingleObject( hThread, INFINITE );CloseHandle( hThread );return 0;}