下面的程序是根据《WIN32多线程程序设计》修改得到的:
#include "stdafx.h"
#include
#include
#include
#include
#include
#include
#include
#include
#define MY_MSG WM_USER+100
HANDLE 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;
}
WM_QUIT的困扰
最新推荐文章于 2022-01-18 11:28:55 发布
6878

被折叠的 条评论
为什么被折叠?



