Perform Action whilst LeftButton is HELD C#

51 Views Asked by At

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.

0

There are 0 best solutions below