前一段時間看見別人做的一個自動填寫信息並且點擊登錄的程序,覺得很有意思。
其實就是在程序中調用Windows的API,那么如何調用,下面就做個簡單的介紹。
寫的簡單粗暴, 不喜輕噴。
0、首先引入名稱空間System.Runtime.InteropServices用來導入Windows DLL.
1、下面是函數原型:
1.1、這是模擬鼠標按下的方法
[DllImport("user32.dll", EntryPoint = "mouse_event")] public static extern void mouse_event( int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo );
1.2、這是模擬按鍵 按下的方法
[DllImport("user32.dll", EntryPoint = "keybd_event")] public static extern void keybd_event( byte bVk, // 虛擬鍵碼 byte bScan, // 該鍵的硬件掃描碼(一般為0 ) dword dwFlags, // 函數操作的各個方面的一個標志位集 dword dwExtralnfo // 與擊鍵相關的附加的32位值 );
PS: 其中第三個參數有三種取值:
-
-
- 0:按下;
- 1:擴展鍵;
- 2:彈起。
-
3.相關實例
const int MOUSEEVENTF_MOVE = 0x0001; //移動鼠標 const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模擬鼠標左鍵按下 const int MOUSEEVENTF_LEFTUP = 0x0004; //模擬鼠標左鍵抬起 const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模擬鼠標右鍵按下 const int MOUSEEVENTF_RIGHTUP = 0x0010; //模擬鼠標右鍵抬起 const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; //模擬鼠標中鍵按下 const int MOUSEEVENTF_MIDDLEUP = 0x0040;// 模擬鼠標中鍵抬起 const int MOUSEEVENTF_ABSOLUTE = 0x8000; //標示是否采用絕對坐標
public Form1() { InitializeComponent(); int X = 100; int Y = 100; mouse_event( MOUSEEVENTF_RIGHTDOWN, X , Y , 0, 0); mouse_event(MOUSEEVENTF_RIGHTUP, X , Y, 0, 0); X += 10; Y += 65; mouse_event(MOUSEEVENTF_MOVE, X, Y , 0, 0); mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y , 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, X, Y , 0, 0); keybd_event(65, 0, 0, 0);//a keybd_event(66, 0, 1, 0);//b keybd_event(13, 0, 0, 0);//回車 }
4、一個很實用的例子(實現了粘貼復制的功能)
//相當於按下 Ctrl+C
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.ControlKey), 0, 0, 0); //按下Ctrl
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.C), 0, 0, 0);
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.ControlKey), 0, 0x2, 0);//彈起Ctrl,*******很重要,不然Ctrl會一直處於按下狀態,鍵盤就是失靈,我自己的親身經歷。。
//相當於按下 Ctrl+V
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.ControlKey), 0, 0, 0); //按下Ctrl
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.V), 0, 0, 0);
keybd_event(Convert.ToInt32(System.Windows.Forms.Keys.ControlKey), 0, 0x2, 0);//彈起Ctrl
5、其實Windows API還有很多,這里只說到了兩種,下面這些也挺常見
[DllImport("user32.dll")]private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")]private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")]private static extern IntPtr FindWindow(string lpClassName,string lpWindowName); [DllImport("user32.dll")]private static extern int SendMessage(IntPtr hWnd,int Msg,int wParam,int lParam); [DllImport("user32.dll")]private static extern bool SetCursorPos(int X, int Y); [DllImport("user32.dll")]private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
6、補充一些沒有說到的
用C#調用Windows API向指定窗口發送按鍵消息