title: Simulate mouse events from C++ in Windows
body: <p>I have a program running with a touch screen, but because the mouse pointer being "on" the touch screen introduces problems, the Windows-mouse behavior of the touch screen has been disabled, and a home-grown program is being used to monitor the touch screen and post messages to the window at the location the screen was touched or untouched (ie. <code>WM_LBUTTONDOWN</code>, <code>WM_LBUTTONUP</code>).</p>
  
  <p>The relevant code looks something like this:</p>
  
  <pre><code>touched = false;
  
  while (1)
  {
      if (!touched) {
          // p.x and p.y calculated here based on mouse position at
          // time of touch screen event
          p.x = ...;
          p.y = ...;
  
          if ((window = WindowFromPoint (p)) != NULL)
              PostMessage (window, WM_LBUTTONDOWN, 0, 0);
  
          touched = true;
      }
      else
      {
          if ((window = WindowFromPoint (p)) != NULL)
              PostMessage (window, WM_LBUTTONUP, 0, 0);
  
          touched = false;
      }
  }
  </code></pre>
  
  <p>This works, but doesn't exactly mimic Windows' mouse press behavior -- regardless of the position of the touch when the untouch occurs (ie. if a touch was dragged), the <code>WM_LBUTTONUP</code> is sent to the control that received the <code>WM_LBUTTONDOWN</code>.</p>
  
  <p>What I was trying to do was make it more Windows-like. In any application, open a dialog that has a button on it. Click and hold the mouse on the button, you'll see it depress. Drag the mouse off the button and don't release the mouse, and you'll see the button raise again. Drag the mouse back onto the button and you'll see it depress. If you release the mouse while the pointer is on the button, the button is pressed. If you release the mouse while the pointer is off the button, the button is not pressed.</p>
  
  <p>I set up a low-level mouse hook, and can see that the only mouse events that occur during this sequence are <code>WM_LBUTTONDOWN</code> followed by a series of <code>WM_MOUSEMOVE</code> followed by a <code>WM_LBUTTONUP</code>, regardless of whether the mouse is released on or off the button.</p>
  
  <p>I have tried adding alternative handling for when the mouse is dragged, and have this posting <code>WM_MOUSEMOVE</code> messages, but which control should these be sent to? The button that the <code>WM_LBUTTONDOWN</code> event was originally sent to, or elsewhere? I have tried both the button and the window the button is on, but obviously I've done something wrong as it doesn't seem to work. The best I have been able to achieve is the touch screen button not being "clicked" when I untouch off the button, but the touch screen button is still drawn depressed.</p>
  
  <p>Any suggestions?</p>
  
  <p>Can anyone confirm which events should be sent where during this operation?</p>
  
  <p>Thanks for any advice.</p>