前一段時間看見別人作的一個自動填寫信息而且點擊登陸的程序,以爲頗有意思。html
其實就是在程序中調用Windows的API,那麼如何調用,下面就作個簡單的介紹。函數
寫的簡單粗暴, 不喜輕噴。post
0、首先引入名稱空間System.Runtime.InteropServices用來導入Windows DLL.ui
一、下面是函數原型:url
1.一、這是模擬鼠標按下的方法spa
[DllImport("user32.dll", EntryPoint = "mouse_event")] public static extern void mouse_event( int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo );
1.二、這是模擬按鍵 按下的方法
code
[DllImport("user32.dll", EntryPoint = "keybd_event")] public static extern void keybd_event( byte bVk, // 虛擬鍵碼 byte bScan, // 該鍵的硬件掃描碼(通常爲0 ) dword dwFlags, // 函數操做的各個方面的一個標誌位集 dword dwExtralnfo // 與擊鍵相關的附加的32位值 );
3.相關實例
orm
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);//回車 }
四、一個很實用的例子(實現了粘貼複製的功能)htm
//至關於按下 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
五、其實Windows API還有不少,這裏只說到了兩種,下面這些也挺常見blog
[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);
六、補充一些沒有說到的