Mouse move in game window by outer C# code

2019-05-18 21:53发布

问题:

I am playing a game, every time I need to move mouse and click into the game's screen to earn game point, so I am trying to write code by c# to click and move mouse in game's screen automatically .. I got some help, so mouse click problems solved, but I am unable to move mouse in game's screen.. Can you please advice me what should I do ?? Should I use "SetWindowsHookEx" or other methods to move mouse in game window ?? Please advice me what should I do..

"Click" code below which I got, it's working fine :

public class ClickGameScreen
  {

    [DllImport("user32.dll")]
    static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);

    [DllImport("user32.dll")]
    internal static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs,  int cbSize);

    internal struct INPUT
    {
      public UInt32 Type;
      public MOUSEKEYBDHARDWAREINPUT Data;
    }

    [StructLayout(LayoutKind.Explicit)]
    internal struct MOUSEKEYBDHARDWAREINPUT
    {
      [FieldOffset(0)]
      public MOUSEINPUT Mouse;
    }

    internal struct MOUSEINPUT
    {
      public Int32 X;
      public Int32 Y;
      public UInt32 MouseData;
      public UInt32 Flags;
      public UInt32 Time;
      public IntPtr ExtraInfo;
    }

    public static void ClickScreen(IntPtr W_Handle , Point C_Point)
    {
      var oldPos = Cursor.Position;
      ClientToScreen(W_Handle, ref C_Point);
      Cursor.Position = new Point(C_Point.X, C_Point.Y);

      var inputDown = new INPUT();
      inputDown.Type = 0;
      inputDown.Data.Mouse.Flags = 0x0002;

      var inputUp = new INPUT();
      inputUp.Type = 0;
      inputUp.Data.Mouse.Flags = 0x0004;

      var inputs = new INPUT[] { inputDown, inputUp };
      SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));

      Cursor.Position = oldPos;
    }

  }

==============

ClickScreen(this.Handle, new Point(375, 340));

===============

回答1:

I solved my problem, code below :

        [DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

        private const int MOUSEEVENTF_MOVE = 0x0001;

        public static void Move(int xDelta, int yDelta)
        {
            mouse_event(MOUSEEVENTF_MOVE, xDelta, yDelta, 0, 0);
        }

//=========================================

Move(830, 160);

//=========================================