November 20, 2011

Simulate A Mouse Click

ถ้าต้องการให้เมาส์คลิกตรงตำแหน่งที่ต้องการโดยอัตโนมัติ สามารถเขียนโปรแกรมช่วยคลิกแทนได้ ดังนี้
ส่วนหัวของโปรแกรมที่จำเป็น :
using System.Windows.Forms;
using System.Runtime.InteropServices;
ตัวอย่างโค้ด :
public partial class Form1 : Form
{
   [DllImport("user32.dll")]
   static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

   private const int MOUSEEVENTF_MOVE = 0x0001;
   private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
   private const int MOUSEEVENTF_LEFTUP = 0x0004;
   private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
   private const int MOUSEEVENTF_RIGHTUP = 0x0010;
   private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
   private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
   private const int MOUSEEVENTF_ABSOLUTE = 0x8000;
        
   public Form1()
   {
      InitializeComponent();
   }

   private void mouse_click_left(int pos_x, int pos_y)
   {
      Cursor.Position = new Point(pos_x, pos_y);
      int X = Cursor.Position.X;
      int Y = Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y, 0, 0);
      mouse_event(MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
   }
   
   private void mouse_click_right(int pos_x, int pos_y)
   {
      Cursor.Position = new Point(pos_x, pos_y);
      int X = Cursor.Position.X;
      int Y = Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_RIGHTDOWN, X, Y, 0, 0);
      mouse_event(MOUSEEVENTF_RIGHTUP, X, Y, 0, 0);
   }
   
   private void mouse_move(int pos_x, int pos_y)
   {
      Cursor.Position = new Point(pos_x, pos_y);
      int X = Cursor.Position.X;
      int Y = Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, X, Y, 0, 0);
   }       
}
ถ้านำไปประยุกต์ใช้งานกับ Timer ก็สามารถสร้างเป็นบอท Auto Click ได้เหมือนกันนะ

1 comment: