title: Why is Windows's SetCursorPos ineffective when certain programs are in foreground?
body: <p>The win32 API's <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setcursorpos" rel="nofollow noreferrer">SetCursorPos</a> moves the mouse to a location on the screen. However, sometimes it does nothing.</p>
  <p>See the following C++ code (Visual Studio 16.8.1, Windows 10)</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;windows.h&gt;
  
  int main()
  {
      while (true)
      {
          std::cout &lt;&lt; &quot;Hello World!\n&quot;;
          SetCursorPos(100, 200);
          Sleep(2000);
      }
  }
  </code></pre>
  <p>Every 2 seconds, if <code>SetCursorPos</code> works then the cursor teleports to <code>(100, 200)</code>. This works normally.</p>
  <p>However if I leave this running and open the built-in Windows app called &quot;On-Screen Keyboard&quot;, <code>SetCursorPos</code> no longer works (the cursor no longer teleports every 2 seconds).<br />
  <em>Note: If trying this yourself, On-Screen Keyboard usually unfocuses itself automatically. To keep it focused to observe <code>SetCursorPos</code> not working, <code>alt+tab</code> to it, which causes it not to unfocus itself.</em></p>
  <p>There are other third-party applications that, when in foreground, also seem to obstruct <code>SetCursorPos</code>. (When I observed those, I wasn't using the above C++ script. I was using the Python package <a href="https://github.com/boppreh/mouse/" rel="nofollow noreferrer"><code>mouse</code></a> which uses <code>SetCursorPos</code> under the hood.)</p>
  <p><strong>How are these applications able to &quot;swallow&quot; my <code>SetCursorPos</code> API calls, and is there a different API or technique I can use in place of <code>SetCursorPos</code> to not allow those applications to interfere?</strong></p>
  <hr />
  <p>A physical USB mouse, as well as remote desktop software such as TeamViewer and Anydesk, are not obstructed by such applications, which leads me to believe they utilize some pathway besides <code>SetCursorPos</code> to get reliable mouse movement.</p>