C# winform 模擬鍵盤輸入自動(dòng)接入訪問網(wǎng)絡(luò)的實(shí)例
背景:
由于所在辦公室網(wǎng)絡(luò)限制,筆者每天都使用網(wǎng)絡(luò)都要先連接無線網(wǎng)。如下圖,輸入授權(quán)用戶信息登錄后才能使用WIFI。
喪心病狂的是該網(wǎng)頁Cookie 過期時(shí)間為24小時(shí),所以每天重復(fù)以下動(dòng)作:打開瀏覽器 -> 手動(dòng)輸入 工號密碼、密碼 -> 點(diǎn)擊“登錄”按鈕。
作為一個(gè)懶出天際的程序員,逃避這種重復(fù)勞動(dòng)是必須滴~~
解決方案:
創(chuàng)建一個(gè)C# 應(yīng)用程序,使用WebBrowser控件加載該頁面,模擬鍵盤輸入賬號、密碼,把用戶配置分別賦值給兩個(gè)控件,然后調(diào)用按鈕的點(diǎn)擊事件。
具體步驟:
1. 打開登錄頁面,按F12查看網(wǎng)頁源碼,可以看到2個(gè)輸入控件名分別為 "user", "password",登錄按鈕名為"Login",如下圖:
2. 模擬事件
模擬過程具體又可分為以下4個(gè)步驟:
step 1. 讀取配置文件中的 登錄網(wǎng)址
step 2. 加載網(wǎng)頁
step 3. 模擬鍵盤操作
step 4. 退出程序
關(guān)鍵部分代碼
/// <summary>
/// 加載網(wǎng)頁,模擬登錄動(dòng)作處理
/// </summary>
private void ProcessLogin()
{
// 驗(yàn)證配置文件
if (string.IsNullOrEmpty(url))
{
ShowMsg("配置文件錯(cuò)誤");
return;
}
ShowMsg("正在加載登錄網(wǎng)頁...");
// 加載網(wǎng)頁
webBrowser1.Navigate(url);
//等待瀏覽器控件加載完成
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
ShowMsg("加載完畢!");
//模擬登錄事件
LoginSimulation(webBrowser1);
}
//模擬登錄事件
private void LoginSimulation(WebBrowser wb)
{
try
{
ShowMsg(string.Format("賬戶名:[{0}],輸入賬戶密碼...", userName));
ShowMsg(string.Format("請確保配置文件中的用戶及登錄密碼準(zhǔn)確可用"));
// 網(wǎng)頁元素
HtmlDocument doc = wb.Document;
HtmlElement emuser = doc.GetElementById("user");
SetHtmlValue(emuser, userName);//設(shè)置賬戶
HtmlElement empassword = doc.GetElementById("password");
SetHtmlValue(empassword, password);//設(shè)置密碼
HtmlElement btn = doc.GetElementById("Login");
InvokeMethod(btn, "click");//調(diào)用 登錄按鈕的 Click 事件 提交配置
ShowMsg("完成!");
TimeSpan used = DateTime.Now - begin;//用時(shí)
ShowMsg(string.Format("用時(shí): {0}.{1}s" , used.Seconds, used.Milliseconds));
ShowMsg("即將自動(dòng)退出...");
//啟動(dòng)計(jì)時(shí)器,4s 后自動(dòng)退出當(dāng)前程序
Timer timer = new Timer();
timer.Interval = 4000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
編譯應(yīng)用程序,把快捷方式添加到開機(jī)啟動(dòng)項(xiàng)。這樣開機(jī)時(shí)就會(huì)自動(dòng)運(yùn)行程序接入網(wǎng)絡(luò)啦?。。?/p>
不足之處:
1. 接入網(wǎng)絡(luò)成功后網(wǎng)頁會(huì)彈出如下的對話框,因此模擬登錄成功后也會(huì)啟動(dòng)瀏覽器打開頁面。如果能禁用就更好了。
2. 只能簡單地提示模擬操作完成,調(diào)用登錄按鈕事件后沒有檢測是否登錄成功。
關(guān)于以上2點(diǎn)不足,如果有人找到解決辦法,就請大膽大意地私信筆者或留言吧 ^_^
適用場景:
本應(yīng)用演示了如何在客戶端加載頁面并模擬鍵盤鼠標(biāo)操作,適用于用戶訪問許可配置保存于服務(wù)器的登錄網(wǎng)站,那些配置要保存到 Session(會(huì)話)的網(wǎng)站訪問 例如淘寶登錄 就不適用了,除非繼續(xù)使用應(yīng)用程序中的 WebBrowser 控件操作而不用外部瀏覽器。
附 界面全部代碼及運(yùn)行截圖
(代碼有點(diǎn)亂,將就著看 -_-|||)
后臺代碼:
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace LoginAssistant
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
readConfigFile();
ProcessLogin();
}
/// <summary>
/// 加載網(wǎng)頁,模擬登錄動(dòng)作處理
/// </summary>
private void ProcessLogin()
{
// 驗(yàn)證配置文件
if (string.IsNullOrEmpty(url))
{
ShowMsg("配置文件錯(cuò)誤");
return;
}
ShowMsg("正在加載登錄網(wǎng)頁...");
// 加載網(wǎng)頁
webBrowser1.Navigate(url);
//等待瀏覽器控件加載完成
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
ShowMsg("加載完畢!");
//模擬登錄事件
LoginSimulation(webBrowser1);
}
//模擬登錄事件
private void LoginSimulation(WebBrowser wb)
{
try
{
ShowMsg(string.Format("賬戶名:[{0}],輸入賬戶密碼...", userName));
ShowMsg(string.Format("請確保配置文件中的用戶及登錄密碼準(zhǔn)確可用"));
// 網(wǎng)頁元素
HtmlDocument doc = wb.Document;
HtmlElement emuser = doc.GetElementById("user");
SetHtmlValue(emuser, userName);//設(shè)置賬戶
HtmlElement empassword = doc.GetElementById("password");
SetHtmlValue(empassword, password);//設(shè)置密碼
HtmlElement btn = doc.GetElementById("Login");
InvokeMethod(btn, "click");//調(diào)用 登錄按鈕的 Click 事件 提交配置
ShowMsg("完成!");
TimeSpan used = DateTime.Now - begin;//用時(shí)
ShowMsg(string.Format("用時(shí): {0}.{1}s" , used.Seconds, used.Milliseconds));
ShowMsg("即將自動(dòng)退出...");
//啟動(dòng)計(jì)時(shí)器,4s 后自動(dòng)退出當(dāng)前程序
Timer timer = new Timer();
timer.Interval = 4000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
//自動(dòng)退出
void timer_Tick(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// 調(diào)用 Html 元素的方法
/// </summary>
/// <param name="em"></param>
/// <param name="methodname"></param>
private void InvokeMethod(HtmlElement em, string methodname)
{
if (em == null) return;
object response = em.InvokeMember(methodname); //觸發(fā)submit事件
}
//賦值于 Html 元素
private void SetHtmlValue(HtmlElement em, string valueStr)
{
if (em == null) return;
em.SetAttribute("value", valueStr);
}
//讀取配置文件
private void readConfigFile()
{
try
{
if(!File.Exists(fileName))return;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
StreamReader m_streamReader = new StreamReader(fs);
m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
string strLine = m_streamReader.ReadLine();
while (strLine != null)
{
string[] data = strLine.Split('=');
switch (data[0])
{
case "user":
userName = getValue(data);
break;
case "password":
password = getValue(data);
break;
case "url":
url = getValue(data);
break;
default:
break;
}
strLine = m_streamReader.ReadLine();
}
m_streamReader.Close();
fs.Close();
}
}
catch (Exception ex)
{
ShowMsg(ex.Message);
}
}
/// <summary>
/// 獲取取配置文件節(jié)點(diǎn)值
/// </summary>
/// <param name="arrays"></param>
/// <returns></returns>
private string getValue(string[] arrays)
{
StringBuilder sb = new StringBuilder();
sb.Append(arrays[1]);
for (int i = 2; i < arrays.Length; i++)
{
sb.Append("=" + arrays[i]);
}
return sb.ToString();
}
/// <summary>
/// 顯示信息
/// </summary>
/// <param name="p"></param>
private void ShowMsg(string p)
{
rtbStatus.AppendText(string.Format("[{0}] {1}\r\n",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), p));
}
#region variables
//賬號、密碼
private string userName = "allliangkaiyu"; // default
private string password = "vicky";
private string url = string.Empty; //登錄頁面
string fileName = "WirelessAssistantConfig.ini"; //配置文件名
WebBrowser webBrowser1 = new WebBrowser();//瀏覽器控件
private DateTime begin = DateTime.Now;//當(dāng)前時(shí)刻
#endregion
#region 按鈕事件
//登錄
private void btnRegister_Click(object sender, EventArgs e)
{
ProcessLogin();
}
//退出
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
}
}
designer.cs 代碼:
namespace LoginAssistant
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.btnInput = new System.Windows.Forms.Button();
this.rtbStatus = new System.Windows.Forms.RichTextBox();
this.btnExit = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnInput
//
this.btnInput.Font = new System.Drawing.Font("Consolas", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnInput.Location = new System.Drawing.Point(46, 235);
this.btnInput.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.btnInput.Name = "btnInput";
this.btnInput.Size = new System.Drawing.Size(86, 36);
this.btnInput.TabIndex = 0;
this.btnInput.Text = "重新登錄";
this.btnInput.UseVisualStyleBackColor = true;
this.btnInput.Click += new System.EventHandler(this.btnRegister_Click);
//
// rtbStatus
//
this.rtbStatus.BackColor = System.Drawing.SystemColors.Control;
this.rtbStatus.Dock = System.Windows.Forms.DockStyle.Top;
this.rtbStatus.Location = new System.Drawing.Point(0, 0);
this.rtbStatus.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.rtbStatus.Name = "rtbStatus";
this.rtbStatus.Size = new System.Drawing.Size(322, 229);
this.rtbStatus.TabIndex = 1;
this.rtbStatus.Text = "";
//
// btnExit
//
this.btnExit.Font = new System.Drawing.Font("Consolas", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.btnExit.ForeColor = System.Drawing.Color.Red;
this.btnExit.Location = new System.Drawing.Point(150, 235);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(75, 36);
this.btnExit.TabIndex = 2;
this.btnExit.Text = "退出";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(322, 274);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.rtbStatus);
this.Controls.Add(this.btnInput);
this.Font = new System.Drawing.Font("Consolas", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "MainForm";
this.Text = "無線網(wǎng)絡(luò)助手 V20160908© vicky";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnInput;
private System.Windows.Forms.RichTextBox rtbStatus;
private System.Windows.Forms.Button btnExit;
}
}
運(yùn)行截圖:
原文鏈接:http://www.cnblogs.com/EasyInvoice/p/6070563.html
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
上一篇:C#多線程編程詳解
欄 目:C#教程
下一篇:C#獲取路由器外網(wǎng)IP,MAC地址的實(shí)現(xiàn)代碼
本文標(biāo)題:C# winform 模擬鍵盤輸入自動(dòng)接入訪問網(wǎng)絡(luò)的實(shí)例
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6174.html
您可能感興趣的文章
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新聞效果的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法
- 01-10WinForm實(shí)現(xiàn)自定義右下角提示效果的方法
- 01-10.net2.0+ Winform項(xiàng)目實(shí)現(xiàn)彈出容器層
- 01-10winform 實(shí)現(xiàn)控制輸入法
- 01-10WinForm實(shí)現(xiàn)程序一段時(shí)間不運(yùn)行自動(dòng)關(guān)閉的方法
- 01-10Winform消除button按下出現(xiàn)的虛線簡單實(shí)現(xiàn)方法


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery


