日常登录网页邮箱或者一些网站,往往需要录入用户名、密码等才能登录,稍嫌繁琐,所以近日研究使用C#自动登录,发现C#可以调用API模拟手工自动登录。本文演示使用C#自动登录网易163邮箱。
界面如下:
点击【登录】按钮后将自动打开IE,然后根据指定的信息,登入163邮箱。
代码如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Threading;
- namespace iSchedule
- {
- public partial class Form3 : Form
- {
- [DllImport("user32.dll")]
- static extern IntPtr SetActiveWindow(IntPtr hWnd);
- [DllImport("user32.dll")]
- [return: MarshalAs(UnmanagedType.Bool)]
- static extern bool SetForegroundWindow(IntPtr hWnd);
- public Form3()
- {
- InitializeComponent();
- }
- private void btnLogin_Click(object sender, EventArgs e)
- {
- Process proc = Process.Start("IExplore.exe", "http://mail.163.com");
- SetActiveWindow(proc.MainWindowHandle);//激活窗口
- SetForegroundWindow(proc.MainWindowHandle);//将窗口放置到前端显示
- Thread.Sleep(1000);//等待1000毫秒(1秒),用于等待网页完全打开
- SendKeys.SendWait("demo@163.com");//自动录入邮箱账号
- SendKeys.SendWait("{tab}");//自动录入TAB键,用于录入账号后,切换至密码框
- SendKeys.SendWait("pwd_haha");//自动录入密码
- SendKeys.SendWait("{ENTER}");//输入回车键,提交数据登录
- }
- }
- }
转载于:https://blog.51cto.com/zhangkui/553519