0

NOTE: I'm quite new to this so if I'm making dumb mistakes I apologise, I'm learning! :D

So basically I want to perform an action whilst the LeftButton on the mouse is held, in my case I would like the program to perform a LeftClick whilst this is true. I have done the following:

  [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);

  private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
  private const int MOUSEEVENTF_LEFTUP = 0x0004;

  bool isDown = false;

  private void mouseMoveEventHandler(object sender, MouseEventArgs e)
  {
        if (e.Button == MouseButtons.Left)
        {
            isDown = true;
        }
        else
        {
            isDown = false;
        }
    }
    //send click
    public void send()
    {
        while (isDown == true){
            int dly = 100;
            txtDly.Text = dly.ToString();
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
            System.Threading.Thread.Sleep(dly);
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
        }
    }

This currently isn't working for me, also, does the click event only happen when I'm on the form? Or will it perform a click anywhere on my computer?

Thanks for any help and sorry if this is a dumb question.

RAD140
  • 61
  • 2
  • 7
  • The click event will happen where ever the mouse pointer is on the screen, if it is on top of a form it will click on the form. What about this doesn't work for you? Does it not enter the `while` loop? if so, it's probably because you aren't initializing `isDown` – Ryan Wilson Dec 06 '18 at 14:33
  • @RyanWilson Hey, thanks for the reply - The click event doesn't seem to be happening anywhere, I tried it on an online click tester with no result. (I have edited the declaration line for the boolean as suggested) – RAD140 Dec 06 '18 at 15:56
  • If you initialize to `false` your loop will never be entered. – Ryan Wilson Dec 06 '18 at 16:14
  • @RyanWilson Okay, I realised the problem is with the mouseMoveEventHandler, I remove this method and set the boolean to true and the program clicked fine. Do you know anything wrong with the mouseMoveEvenHandler, do I need to call it anywhere? – RAD140 Dec 06 '18 at 17:10
  • I wouldn't name the method `mouseMoveEventHandler` when you are actually handling mouse button clicks. – Ryan Wilson Dec 06 '18 at 17:18

0 Answers0