title: WndProc calling mechanism (WinAPI)
body: <p>I'm trying to understand how a windows application works.</p>
  
  <p>There is a WndProc function, wherein message processing occurs.</p>
  
  <pre><code>LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {   
      switch (msg) {
          case WM_KEYDOWN:
              if (wParam == VK_ESCAPE) {                                              
                  if (MessageBox(0, L"Are you sure?", L"Exit?", MB_YESNO |     MB_ICONQUESTION) == IDYES)
                      //Release the windows allocated memory  
                      DestroyWindow(hwnd);
              }
              return 0;
  
          case WM_DESTROY:
              PostQuitMessage(0);
              return 0;
      }
      return DefWindowProc(hwnd, msg, wParam, lParam);
  }
  </code></pre>
  
  <p>This function can be called in two cases:</p>
  
  <p>A) Called by DispatchMessage(&amp;msg) function in a message loop cycle:</p>
  
  <pre><code>while (true){                       
          if (PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE)){
              if (msg.message == WM_QUIT)    
                  break;   
              TranslateMessage(&amp;msg);                                     
              DispatchMessage(&amp;msg);
          }
      }
  </code></pre>
  
  <p>B) Called by Windows when receiving a non-queued message.</p>
  
  <p>How does this work? How does Windows immediately call the WndProc function without using parallelism? Could you please describe in detail the mechanism of function calls?</p>
  
  <p>The official MSDN documentation says:</p>
  
  <blockquote>
    <p>Nonqueued messages are sent immediately to the destination window procedure, bypassing the system message queue and thread message queue. The system typically sends nonqueued messages to notify a window of events that affect it. For example, when the user activates a new application window, the system sends the window a series of messages, including WM_ACTIVATE, WM_SETFOCUS, and WM_SETCURSOR. These messages notify the window that it has been activated, that keyboard input is being directed to the window, and that the mouse cursor has been moved within the borders of the window. Nonqueued messages can also result when an application calls certain system functions. For example, the system sends the WM_WINDOWPOSCHANGED message after an application uses the SetWindowPos function to move a window.</p>
  </blockquote>
  
  <p>It turns out that non-queued messages appear only during initialization of the window, and all subsequent non-queued messages can only be the result of calling WinAPI functions in my program?</p>