日常登录网页邮箱或者一些网站,往往需要录入用户名、密码等才能登录,稍嫌繁琐,所以近日研究使用C#自动登录,发现C#可以调用API模拟手工自动登录。本文演示使用C#自动登录网易163邮箱。

界面如下:

 

 

点击【登录】按钮后将自动打开IE,然后根据指定的信息,登入163邮箱。

代码如下:

 

 
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9.  
  10. using System.Runtime.InteropServices;  
  11. using System.Diagnostics;  
  12. using System.Threading;  
  13.  
  14.  
  15.  
  16. namespace iSchedule  
  17. {  
  18.     public partial class Form3 : Form  
  19.     {  
  20.         [DllImport("user32.dll")]  
  21.         static extern IntPtr SetActiveWindow(IntPtr hWnd);  
  22.         [DllImport("user32.dll")]  
  23.         [return: MarshalAs(UnmanagedType.Bool)]  
  24.         static extern bool SetForegroundWindow(IntPtr hWnd);   
  25.  
  26.         public Form3()  
  27.         {  
  28.             InitializeComponent();  
  29.         }  
  30.  
  31.         private void btnLogin_Click(object sender, EventArgs e)  
  32.         {  
  33.             Process proc = Process.Start("IExplore.exe""http://mail.163.com");  
  34.  
  35.             SetActiveWindow(proc.MainWindowHandle);//激活窗口  
  36.  
  37.             SetForegroundWindow(proc.MainWindowHandle);//将窗口放置到前端显示  
  38.  
  39.  
  40.             Thread.Sleep(1000);//等待1000毫秒(1秒),用于等待网页完全打开  
  41.  
  42.             SendKeys.SendWait("demo@163.com");//自动录入邮箱账号  
  43.  
  44.             SendKeys.SendWait("{tab}");//自动录入TAB键,用于录入账号后,切换至密码框  
  45.  
  46.             SendKeys.SendWait("pwd_haha");//自动录入密码  
  47.  
  48.             SendKeys.SendWait("{ENTER}");//输入回车键,提交数据登录  
  49.  
  50.         }  
  51.     }  
  52. }