Cursor.Postition and Mouse_Event being Blocked

2019-08-03 16:18发布

问题:

I'm working on an app to automate some input into another application. And i'm running into a problem. Below is the function code i'm using

public class MouseClick
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
}

public enum MouseButton
{
    MOUSEEVENTF_LEFTDOWN = 0x02,
    MOUSEEVENTF_LEFTUP = 0x04,
    MOUSEEVENTF_RIGHTDOWN = 0x08,
    MOUSEEVENTF_RIGHTUP = 0x10
}

and here is the code i'm using to move and click

Point LocPoint = GetLocation(Column, Row, Item);
Console.WriteLine("Column: {0}\tRow: {1}\tItem: {2}\tPoints: {3}\tCursor: {4}", Column, Row, Item, Points, LocPoint.X + "," + LocPoint.Y);

Thread.Sleep(200);
Cursor.Position = LocPoint;
Thread.Sleep(10);

MouseClick.mouse_event((int)MouseButton.MOUSEEVENTF_LEFTDOWN | (int)MouseButton.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Thread.Sleep(200);

However here is where things get interesting when I don't have the application I want to input into as the active window but say mspaint the code runs fine and I get dots from the paint brush where I want to click however when the application I want to run this in is active the mouse doesn't ever move and no click is registered it is as if the application is intercepting these calls and ignoring them. So this leads me to two questions

  1. Is this possible? How does it detect difference between a mouse and setting the cords
  2. Is there a way around this or another method to use?

Ok so everyone is telling me to use SendInput instead. Ok so I changed the code to use SendInput. I've also tried C# SendKeys as a test as well. Currently I've gone back to the basic and i'm just trying to input the letter A into a text input box that I make the target manually. When I run it in Notepad both SendInput and SendKeys both type the letter A however when i'm inside the other application i'm trying to automate this to nothing shows up. Here is the SendInput code i'm using.

INPUT[] Inputs = new INPUT[2];
Inputs[0].type = WindowsAPI.INPUT_KEYBOARD;
Inputs[0].ki.wVk = 0;
Inputs[0].ki.dwFlags = WindowsAPI.KEYEVENTF_UNICODE;
Inputs[0].ki.wScan = 0x41;

Inputs[0].type = WindowsAPI.INPUT_KEYBOARD;
Inputs[0].ki.wVk = 0;
Inputs[1].ki.dwFlags = WindowsAPI.KEYEVENTF_KEYUP;
Inputs[0].ki.wScan = 0x41;

WindowsAPI.SendInput((uint)Inputs.Length, Inputs, Marshal.SizeOf(Inputs[0]));

回答1:

So after just frustration I decided to run the app outside of Visual Studio's debug mode which resulted in the same result nothing. However I decided to run the app "As Administrator" even through I have UAC turned all the down and to my surprise the application properly moved the mouse, clicked and inputted text. I do not know why this is required as I've pinvoked methods before and never had to do this however that seems to be the solution.