title: Checking for messages in windowless application
body: <p>I have a small application that needs to react to a particular device being added or removed from the system. So I listen for <code>WM_DEVICECHANGE</code> using <code>CreateWindowEx()</code> and <code>RegisterDeviceNotification()</code>.</p>
  <p>This seems to work - however, I am left uncertain about how I properly check the message queue. This, in short, is my current approach:</p>
  <pre><code>procedure Main();
  
    procedure HandleMessages(aWndHandle: HWND);
    var
      lpMsg: TMsg;
    begin
      while PeekMessage(lpMsg, aWndHandle, 0, 0, PM_REMOVE) do
        DispatchMessage(lpMsg);  
    end;
  
  begin
    // ...  
    if (RegisterClassEx(wClass) = 0) then System.Exit;
    wndHnd := CreateWindowEx(0, PChar(wClass.lpszClassName), nil, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, HInstance, nil);
    // ...
    notificationHandle := RegisterDeviceNotification(wndHnd, @bcInterface, DEVICE_NOTIFY_WINDOW_HANDLE);
  
    while True do
    begin
      HandleMessages();
      DoThings();
  
      HandleMessages();
      DoOtherThings();
  
      HandleMessages();
      DoYetMoreThings();
    end;
  
    // ... (cleanup)
  end;
  
  </code></pre>
  <p>Is this <code>while True do</code> loop with repeated calls to <code>HandleMessages()</code> viable? Or do I need to worry about some hidden problems - such as, if one of the <code>DoThings()</code> routines were to take a long time to return?<br />
  It just seems somewhat awkward to me and I (suspiciously...) don't seem to be able to find any comparable examples online...</p>
  <p>Edit: This application has no UI or console and no interaction. It reads the input from an HID scanner and needs to know if the scanner is removed or added to the system. It runs until the user logs off.</p>