+ Reply to Thread
Results 1 to 2 of 2

Thread: How to create a thread without window and still has GetMessage loop?

  1. #1

    How to create a thread without window and still has GetMessage loop?

    Hello,

    I want this to have inter process communication between two threads in the application. How can I do this?

    Thanks in advance.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    You can create a thread using AfxBeginThread or _beginthreadex or CreateThread API.

    Use PostThreadMessage API to send a message to thread.

    Example:

    Code:
    #define MESSAGE_1		10000
    #define MESSAGE_2		10001
    #define MESSAGE_3		10002
    #define MESSAGE_DESTROY	10003
    
    UINT ThreadFunction(LPVOID lpVoid)
    {
    	char szMessage[1024] ;
    	MSG msg ;
    	BOOL bContinue = TRUE ;
    	while(GetMessage(&msg, NULL, 0, 0))
    	{
    		switch(msg.message)
    		{
    		case MESSAGE_1:
    			{
    				sprintf(szMessage, "Received Mesage. Message ID is : %d\n", msg.message) ;
    				OutputDebugString(szMessage) ;
    			}
    			break ;
    		case MESSAGE_2:
    			{
    				sprintf(szMessage, "Received Mesage. Message ID is : %d\n", msg.message) ;
    				OutputDebugString(szMessage) ;
    			}
    			break ;
    		case MESSAGE_3:
    			{
    				sprintf(szMessage, "Received Mesage. Message ID is : %d\n", msg.message) ;
    				OutputDebugString(szMessage) ;
    			}
    			break ;
    		case MESSAGE_DESTROY:
    			{
    				sprintf(szMessage, "Destroy message received. Message ID is : %d\n", msg.message) ;
    				OutputDebugString(szMessage) ;
    				bContinue = FALSE ;
    			}
    			break ;
    		default:
    			{
    				sprintf(szMessage, "Invalid Message\n", msg.message) ;
    				OutputDebugString(szMessage) ;
    			}
    			break ;
    		}
    
    		if (!bContinue)
    		{
    			break ;
    		}
    	}
    
    	AfxEndThread(0, TRUE) ;
    
    	return 0 ;
    }
    
    BOOL CMyDlg::OnInitDialog()
    {
    	CDialog::OnInitDialog();
    
    	m_pWinThread = AfxBeginThread(ThreadFunction, NULL) ;
    }
    
    void CMyDlg::OnOK() 
    {
            //send message to the thread...
    	if(NULL != m_pWinThread)
    	{
    		static int nMesageID = MESSAGE_1 ;
    		PostThreadMessage(m_pWinThread->m_nThreadID, nMesageID, 0, 0) ;
    		nMesageID++ ;
    	}
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts