The technique illustrated in Receiving a Message to receive message has a significant drawback. As long as the process is waiting to receive a message, it can do nothing else. In other words, the message queue holds the process thread hostage. An alternative is to establish an MSMQEvent object that allows your application to respond to incoming messages as events that are raised through this object. The code below shows an example of how to accomplish this. Be aware that there are actually three parts to this code. The first two lines are in the General Declaration portion of the form. They are followed by the Form_Load and event procedures.
Private RequestQ As MSMQQueue
Private WithEvents RequestEvent As MSMQEvent
Private Sub Form_Load()
Dim QI As New MSMQQueueInfo
QI.PathName = "MyServer\QueueName"
Set RequestQ = QI.Open(MQ_RECEIVE_ACCESS, MQ_DENY_NONE)
Set RequestEvent = New MSMQEvent
Sub RequestEvent_Arrived(ByVal Queue as Object, ByVal Cursor As Long)
Dim InQueue As MSMQQueue
Dim msg As MSMQMessage
Set InQueue = Queue
Set msg = InQueue.Receive(ReceiveTimeOut:=0)
If Not msg is Nothing Then
' Process the message
In this example, the EnableNotification method is used to associate an MSMQEvent object with a queue. This causes the Arrived event to be triggered whenever a message is posted to that queue. You should also notice that the EnableNotification method was called again at the bottom of the Arrived procedure. That is because EnableNotification only sets up the event for the next message.