C# winform 加載網頁 模擬鍵盤輸入自動接入訪問網絡


聲明:

本文原創,首發於博客園 http://www.cnblogs.com/EasyInvoice/p/6070563.html 轉載請注明出處。

背景:

由於所在辦公室網絡限制,筆者每天都使用網絡都要先連接無線網。如下圖,輸入授權用戶信息登錄后才能使用WIFI。

喪心病狂的是該網頁Cookie 過期時間為24小時,所以每天重復以下動作:打開瀏覽器 -> 手動輸入 工號密碼、密碼 -> 點擊“登錄”按鈕。

作為一個懶出天際的程序員,逃避這種重復勞動是必須滴~~

解決方案:

創建一個C# 應用程序,使用WebBrowser控件加載該頁面,模擬鍵盤輸入賬號、密碼,把用戶配置分別賦值給兩個控件,然后調用按鈕的點擊事件。

具體步驟:

1. 打開登錄頁面,按F12查看網頁源碼,可以看到2個輸入控件名分別為 "user", "password",登錄按鈕名為"Login",如下圖:

2. 模擬事件

模擬過程具體又可分為以下4個步驟:

step 1. 讀取配置文件中的 登錄網址、賬號、密碼

step 2. 加載網頁

step 3. 模擬鍵盤操作

step 4. 退出程序

關鍵部分代碼

        /// <summary>
        /// 加載網頁,模擬登錄動作處理
        /// </summary>
        private void ProcessLogin()
        {
            // 驗證配置文件
            if (string.IsNullOrEmpty(url))
            {
                ShowMsg("配置文件錯誤");
                return;
            }

            ShowMsg("正在加載登錄網頁...");
            // 加載網頁
            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("請確保配置文件中的用戶及登錄密碼准確可用"));

                // 網頁元素
                HtmlDocument doc = wb.Document;
                HtmlElement emuser = doc.GetElementById("user");
                SetHtmlValue(emuser, userName);//設置賬戶
                HtmlElement empassword = doc.GetElementById("password");
                SetHtmlValue(empassword, password);//設置密碼
                HtmlElement btn = doc.GetElementById("Login");
                InvokeMethod(btn, "click");//調用 登錄按鈕的 Click 事件 提交配置

                ShowMsg("完成!");
                TimeSpan used = DateTime.Now - begin;//用時
                ShowMsg(string.Format("用時: {0}.{1}s" , used.Seconds, used.Milliseconds));
                ShowMsg("即將自動退出...");

                //啟動計時器,4s 后自動退出當前程序
                Timer timer = new Timer();
                timer.Interval = 4000;
                timer.Tick += new EventHandler(timer_Tick);
                timer.Start();
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }

   

 編譯應用程序,把快捷方式添加到開機啟動項。這樣開機時就會自動運行程序接入網絡啦!!!

不足之處:

1. 接入網絡成功后網頁會打開如下的頁面,因此模擬登錄成功后也會啟動瀏覽器打開頁面。如果能禁用就更好了。

 

 2. 只能簡單地提示模擬操作完成,調用登錄按鈕事件后沒有檢測是否登錄成功。

關於以上2點不足,如果有人找到解決辦法,就請大膽大意地私信筆者或留言吧 ^_^

適用場景:

本應用演示了如何在客戶端加載頁面並模擬鍵盤鼠標操作,適用於用戶訪問許可配置保存於服務器的登錄網站,那些配置要保存到 Session(會話)的網站訪問 例如 某寶網站登錄 就不適用了,除非繼續使用應用程序中的 WebBrowser 控件操作而不用外部瀏覽器。

附 界面全部代碼及運行截圖

(代碼有點亂,將就着看 -_-|||)

后台代碼:

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>
        /// 加載網頁,模擬登錄動作處理
        /// </summary>
        private void ProcessLogin()
        {
            // 驗證配置文件
            if (string.IsNullOrEmpty(url))
            {
                ShowMsg("配置文件錯誤");
                return;
            }

            ShowMsg("正在加載登錄網頁...");
            // 加載網頁
            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("請確保配置文件中的用戶及登錄密碼准確可用"));

                // 網頁元素
                HtmlDocument doc = wb.Document;
                HtmlElement emuser = doc.GetElementById("user");
                SetHtmlValue(emuser, userName);//設置賬戶
                HtmlElement empassword = doc.GetElementById("password");
                SetHtmlValue(empassword, password);//設置密碼
                HtmlElement btn = doc.GetElementById("Login");
                InvokeMethod(btn, "click");//調用 登錄按鈕的 Click 事件 提交配置

                ShowMsg("完成!");
                TimeSpan used = DateTime.Now - begin;//用時
                ShowMsg(string.Format("用時: {0}.{1}s" , used.Seconds, used.Milliseconds));
                ShowMsg("即將自動退出...");

                //啟動計時器,4s 后自動退出當前程序
                Timer timer = new Timer();
                timer.Interval = 4000;
                timer.Tick += new EventHandler(timer_Tick);
                timer.Start();
            }
            catch (Exception ex)
            {
                ShowMsg(ex.Message);
            }
        }
        //自動退出
        void timer_Tick(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 調用 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); //觸發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>
        /// 獲取取配置文件節點值
        /// </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;//當前時刻

        #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 = "無線網絡助手 V20160908© vicky";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button btnInput;
        private System.Windows.Forms.RichTextBox rtbStatus;
        private System.Windows.Forms.Button btnExit;
    }
}

  運行截圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM