MsgWaitForMultipleObjects code example

Posted on 1999-01-24
Last Modified: 2012-08-14
I'm looking for a code example that uses MsgWaitForMultipleObjects correctly. I'm only interested in waiting for one object, but this thread creates windows, so I can't use WaitForSingleObject. Every time I've tried doing it, it doesn't return before the timeout, even if the thread's window receives messages. I am passing a pointer to the object I am waiting for (a mutex) as the pHandles parameter. I am using QS_ALLEVENTS as the dwWakeMask parameter.
Question by:covington
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 2

Expert Comment

ID: 1470406
I haven't used it so I don't have an example for U.  Have U seen Appleman's Win32 API book discussion of it's use?  I'm looking at it, and it  doesn't appear to discuss any bizarre requirements - just a thought.


Author Comment

ID: 1470407
That's why I'm asking - I have looked in his book, and it seems simple to use, but I can't get it to work.

BTW, I'm using VB 5.0, SP3.

Author Comment

ID: 1470408
Bueller? Bueller?
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Expert Comment

ID: 1470409
I found this in the samples for McKinney's Hardcore VB book.  Let me know if it works.

Attribute VB_Name = "MFileNotify"
Option Explicit

Public Type TConnection
    sDir As String
    fSubTree As Boolean
    notifier As IFileNotifier
End Type

' Actually cLastNotify + 1 allowed
Public Const cLastNotify = 28
' One extra blank item in each array for easy compacting
Public ahNotify(0 To cLastNotify + 1) As Long
Public aconNotify(0 To cLastNotify + 1) As TConnection
Public aerr(errFirst To errLast) As String
' Count of connected objects managed by class
Public cObject As Long

Sub Main()

    Dim i As Integer
    For i = 0 To cLastNotify
        ahNotify(i) = hInvalid
    aerr(errInvalidDirectory) = "Invalid directory"
    aerr(errInvalidType) = "Invalid notification type"
    aerr(errInvalidArgument) = "Invalid argument"
    aerr(errTooManyNotifications) = "Too many notifications"
    aerr(errNotificationNotFound) = "Notification not found"
    BugMessage "Initialized static data"

    ' Start the wait loop and return to the caller
    Call SetTimer(hNull, 0, 200, AddressOf WaitForNotify)
    BugMessage "Started Timer"
End Sub

Sub WaitForNotify(ByVal hWnd As Long, ByVal iMsg As Long, _
                  ByVal idTimer As Long, ByVal cCount As Long)
    ' Ignore all parameters except idTimer
    ' This one-time callback is used only to start the loop
    KillTimer hNull, idTimer
    BugMessage "Killed Timer"

    Dim iStatus As Long, f As Boolean
    ' Keep waiting for file change events until no more objects
        '  Wait 100 milliseconds for notification
        iStatus = WaitForMultipleObjects(Count, ahNotify(0), _
                                         False, 100)
        Select Case iStatus
        Case WAIT_TIMEOUT
            ' Nothing happened
            BugMessage "Waited for timeout"
        Case 0 To Count
            BugMessage "Got a notification"
            ' Ignore errors from client; that's their problem
            On Error Resume Next
            ' Call client object with information
            With aconNotify(iStatus)
                .notifier.Change .sDir, .efn, .fSubTree
            End With
            ' Wait for next notification
            f = FindNextChangeNotification(ahNotify(iStatus))
            BugAssert f
        Case WAIT_FAILED
            ' Indicates no notification requests
            BugMessage "No notification requests"
        Case Else
            BugMessage "Can't happen"
        End Select
    ' Class Initialize and Terminate events keep reference count
    Loop Until cObject = -1
End Sub

Private Property Get Count() As Long
    Dim i As Long
    For i = 0 To cLastNotify
        If ahNotify(i) = INVALID_HANDLE_VALUE Then Exit For
    Count = i
End Property

Public Sub RaiseError(iErr As Integer)
    Err.Raise vbObjectError + iErr, "FileNotify.CFileNotify", aerr(iErr)
End Sub


Author Comment

ID: 1470410
Sorry, but that's an example with WaitForMultipleObjects. I'm looking for MsgWaitForMultipleObjects.

From the SDK:
"If you have a thread that uses a wait function with no time-out interval, the system will deadlock. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForMultipleObjects."

I've tried using WaitForMultipleObjects in a loop with a short timeout, but the tasks I'm waiting for won't execute when WaitForMultipleObjects is waiting, which defeats the purpose.

Accepted Solution

anzen earned 300 total points
ID: 1470411
I'm assuming You have seen the documents about MsgWait... and that You know how to issue some API calls, the main difference in MsgWait... is that it can check the message queue for the waited object, so if You specify your own process as one of the objects to be waited and set the dwWakeMask parameter to a usable value (say QS_ALLINPUT) whenever a message is into the message queue of Your app the wait will return allowing You to process it and avoiding Your app to hang, oviously in this case You should check the reason of the Wait termination and, if it's the case restart waiting.

I hope it's clear, if not let me know


Author Comment

ID: 1470412
Fairly clear...

Let me try to restate this in my own words...tell me if I get it right.

I was passing just one handle (the mutex) into the MsgWait.. call. I thought that I would also automatically be waiting on any messages that the waiting thread received. You're saying that I won't get these messages unless I pass in both the handle to the mutex and the handle to the waiting thread. Is that right?

I understand the part about checking to see why the wait released, and looping again if it wasn't the mutex.

I'll try it out this weekend and let you know how it works.


Expert Comment

ID: 1470413
You got the point pal, it's exactly as explained into MS docs


Author Comment

ID: 1470414
I'll still try it this weekend, but I'm not sure what MS docs you're referring to. In the SDK for MsgWait... it says:

"The state of a thread object is set to signaled when the thread terminates."

So I imagine that if I wait on a thread, it won't return until the thread terminates. This defeates the purpose, since I can't have a thread wait on itself. Should I be including the thread handle in the array, or the handle of the window (created in the thread) that I expect to receive the posted messages?

Expert Comment

ID: 1470415
Yes I just wrote this, sorry for the misunderstanding, You MUST include Your own process in the wait list to get signaled whenever a message is in Your (main) process queue !!

I got to go now it's 19.24 here (Italy)


Author Comment

ID: 1470416
I haven't forgotten this question - I've just been too swamped to try it recently.

Expert Comment

ID: 1470417
No Prob ... but let me know please !


Author Comment

ID: 1470418
Still haven't tried it, but I don't want this to expire without giving you a decent grade.


Expert Comment

ID: 1470419
Please let me know when You test it, You can reach
me via e-mail at

Bye and ...thank You !


Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to compare ms sql hashbytes results within vb6 5 105
VB6 ListBox Question 4 61
How to read File Date Created using VB6 8 70
Excel Web Add-in Where is Visual Basic used 9 72
Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question