Button cklick in C# .Net

Ghada Alsayed 21 Reputation points
2021-02-24T16:14:08.96+00:00

HI
I wnat help please here is some of description :

Auto Clicker

Description:

I want the program to click while holding down the mouse button and I want it to stop clicking when you release the mouse button.

Visual description

problem:

I can not find anything that you can use to know when you press the mouse button. There are events for this inside the visual studio Forms but they only apply if the program is in focus.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace autoClicker
{
    public partial class Form1 : Form
    {
        [Flags]
        private enum KeyStates
        {
            None = 0,
            Down = 1,
            Toggled = 2
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]

        public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);

        private const int MOUSEEVENTF_LEFTDOWN = 0x02;
        private const int MOUSEEVENTF_LEFTUP = 0x04;
        private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
        private const int MOUSEEVENTF_RIGHTUP = 0x10;

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern short GetKeyState(int keyCode);

        int delay = 0;
        int clicks = 0;

        private Timer timer = new Timer();
        private Timer timer2 = new Timer();
        private Timer timer3 = new Timer();
        private Timer timerCheck = new Timer();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            RefreshDelay();
            timer.Tick += new EventHandler(timer_Tick);
            timerCheck.Tick += new EventHandler(TimerCheck_Tick);
            timerCheck.Interval = 1;
        }

        int extraTime = 0;
        private void TimerCheck_Tick(object sender, EventArgs e)
        {
            extraTime++;
            if (timer.Enabled && extraTime > 5)
            {
                if (delay < 1) delay = 1;
                timer.Interval = delay;
                short retVal = GetKeyState((int)keyValue);
                if ((retVal & 0x8000) == 0x8000)
                {
                    timer.Enabled = false;
                    extraTime = 0;
                }
            }
            else if(!timer.Enabled && extraTime > 5)
            {
                short retVal = GetKeyState((int)keyValue);
                if ((retVal & 0x8000) == 0x8000)
                {
                    timer.Enabled = true;
                    extraTime = 0;
                }
            }
        }

        private void start_Click(object sender, EventArgs e)
        {
            if (delay < 1) delay = 1;
            timer.Interval = delay;
            timer.Enabled = true;
        }

        private void stop_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            DoClick();
        }

        private void DoClick()
        {
            //Call the imported function with the cursor's current position
            uint x = Convert.ToUInt32(Cursor.Position.X);
            uint y = Convert.ToUInt32(Cursor.Position.Y);
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);
        }

        #region Delay
        int deleteMil = 0;
        private void milliseconds_TextChanged(object sender, EventArgs e)
        {
            CreateDelay(milliseconds_T, ref deleteMil, 1);
        }

        int deleteSec = 0;
        private void Seconds_T_TextChanged(object sender, EventArgs e)
        {
            CreateDelay(seconds_T, ref deleteSec, 1000);
        }

        int deleteMin = 0;
        private void Minutes_T_TextChanged(object sender, EventArgs e)
        {
            CreateDelay(minutes_T, ref deleteMin, 60000);
        }

        private void CreateDelay(TextBox textBox, ref int deleteTime, int times)
        {
            string text = textBox.Text;
            int addDelay;
            int.TryParse(text, out addDelay);

            try
            {
                delay -= deleteTime * times;
            }
            catch (Exception d) { }

            delay += addDelay * times;
            total.Text = delay.ToString();
            deleteTime = addDelay;
        }

        private void RefreshDelay()
        {
            CreateDelay(milliseconds_T, ref deleteMil, 1);
            CreateDelay(seconds_T, ref deleteSec, 1000);
            CreateDelay(minutes_T, ref deleteMin, 60000);
        }
        #endregion

        private void test_Click(object sender, EventArgs e)
        {
            clicks++;
            test.Text = "Clicks " + clicks;
        }

        private void hotkey_Click(object sender, EventArgs e)
        {
            hotkey.Text = "Press a Key!";
            KeyDown += new KeyEventHandler(Form1_KeyDown);
        }

        int keyValue;
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            keyValue = e.KeyValue;
            hotkey.Text = "Hotkey: " + e.KeyCode + " " + keyValue;
            KeyDown -= new KeyEventHandler(Form1_KeyDown);
            timerCheck.Start();
            timerCheck.Interval = 1;
        }

        private bool checkMouse = false;
        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            checkMouse = checkBox.Checked;
        }
    }
}



using System;
using System.Windows.Forms;

namespace autoClicker
{
    static class Program
    {

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Thak you for your help.
Regardes

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2021-02-25T00:31:19.273+00:00

    I can not find anything that you can use to know when you press the mouse button. There are events for this inside the visual studio Forms but they only apply if the program is in focus.

    You can use GetAsyncKeyState

    But the problem is that if you simulate Mouse Down/Up, it will return false after the Up

    If you need to click on a button, you can do (test in a timer) :

    bool bLeftButton = (GetAsyncKeyState((int)VK_LBUTTON) & 0x8000) == 0x8000;  
    if (bLeftButton)  
    {                 
        Point pt = System.Windows.Forms.Cursor.Position;  
        IntPtr hWnd = WindowFromPoint(pt);  
        SendMessage(hWnd, BM_CLICK, 0, IntPtr.Zero);              
    }    
    

    Declarations :

    [DllImport("User32.dll", SetLastError = true, CharSet = Ch  
    public static extern short GetAsyncKeyState(int nVirtKey);  
      
    public const int VK_LBUTTON = 0x01;  
      
    [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]                   
    public static extern IntPtr WindowFromPoint(Point pt);                                   
                                                                                             
    public const int BM_CLICK = 0xF5;                                                        
                                                                                             
    [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]                   
    public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);  
      
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-02-25T02:40:42.327+00:00

    There is another way for your reference.

    There is a control in WPF called RepeatButton, we can use it in Windows Forms through simple steps.

    1. Right-click the project => Add => New Item=>User Control(WPF), and add the following code:
          <UserControl x:Class="WindowsFormsApp2.UserControl1"  
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
               xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
               xmlns:local="clr-namespace:WindowsFormsApp2"  
               mc:Ignorable="d"   
               d:DesignHeight="100" d:DesignWidth="200">  
      <Grid>  
          <StackPanel>  
              <RepeatButton x:Name="repBtn" Height="100" Width="200" Delay="500" Interval="100" Click="repBtn_Click">0</RepeatButton>  
          </StackPanel>  
      </Grid>  
      
      </UserControl>
      Code behind:
      public partial class UserControl1 : UserControl  
      {  
          public UserControl1()  
          {  
              InitializeComponent();  
          }  
          int i = 0;  
          private void repBtn_Click(object sender, RoutedEventArgs e)  
          {  
              repBtn.Content = i++;  
          }  
      }  
      
    2. Build the project, and then this control will appear in the Toolbox, and you can use it like other Windows Forms controls.

    71857-1.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Abdulhakim M. Elrhumi 356 Reputation points
    2021-02-25T03:23:55.057+00:00

    Hi

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace TestClick
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
        int i = 0;
        private void button1_MouseHover(object sender, EventArgs e)
        {
           timer1.Enabled = true;
        }
    
        private void button1_MouseLeave(object sender, EventArgs e)
        {
          timer1.Enabled = false;
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
          i++;
          button1.Text = i.ToString();
        }
      }
    }
    

    Best Regards.
    --please don't forget to Accept as answer if the reply is helpful--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.