c# moving mouse not working without focus

1.1k Views Asked by At

I want to move the mouse and simulate mouse clicks outside of my application.

I've tried every possible way of moving the mouse, sendinput, tons of libraries including BotSuite and Input Simulator.

Every time my application loses focus it's not moving the mouse, nor clicking. I can move the mouse, and click inside my application, but as soon as I lose focus it stops working completely. I can not click on anything outside of my application either, even while in focus.

Why is that?

Here's a snippet using BotSuite. I'm starting a process before this and make it the focus.

        Bitmap CapturedScreen = ScreenShot.Create(LauncherHandle);
        Bitmap bmpRefPic = new Bitmap("launchbutton.png");
        ImageData refpic = new ImageData(bmpRefPic);
        ImageData source = new ImageData(CapturedScreen);

        List<Rectangle> found = new List<Rectangle>();

        found = Template.AllImages(source, refpic, 124);

        Mouse.MoveRelativeToWindow(LauncherHandle, found[0].X + 50, found[0].Y + 50, true, 100);

        Mouse.LeftClick();

This is not working. However if I do a SetForegroundWindow on my own Application beforehand, the Mouse.Move command works. Clicking does not work either way outside of my applications boundaries.

2

There are 2 best solutions below

0
On

SendInput places messages into the message queue of the foreground window. So, if your application is the foreground window, then SendInput will place the messages in your application's message queue.

To fake input in another application you need to either:

  1. Make the foreground window be a window in the other application.
  2. Use PostMessage to post input messages directly to the target window.

Option 2 does not always work as you intend because input messages may have quite complex treatment. For mouse messages, this is less likely to be an issue than key messages.

Perhaps it would be simpler for you to use the automation API.

0
On

I'm not sure if it is the same problem, but here's what I wanted to do and how I could fix it:

from an answer to How can I simulate mouse events from code? I've seen that SendInput only works on programs that have less or same integrity level than your application.

I wanted to automatically log in to a game. That game needs to be launched as admin for some HackShield or something. I was wondering why my SendInput worked (tested for keyboard events) on Firefox, but not on that game.

When I focus my app, the right region of the screen was selected, the mouse was moved to that location, but the game didnt get focus. If I focused the game manually, the application computed the right region to click, but neither mouse movement nor click were performed.

Launching my application as admin too, solved the problem and everything worked like charm =)

hope this might help somebody else, too!