這裏就須要委託。 定義一個 委託。加載以後給他綁定一個方法Callback,也就是所說的回掉函數。
而後寫一個線程,線程須要一個object 的參數。將你定義的委託看成參數傳進線程中的方法。
在線程中去計時。作成一個while(true)的循環,循環內停十分鐘,
而後使用beiginInvoke調用委託,天然會觸發主線程中的callback方法。
在callback 方法內,因爲是主線程,你就能夠對你任意的控件進行操做了
Thread t =
null
;
//建立線程,用來定時刷新數據。
CallBackDelegate cbd = null;
public
delegate
void
CallBackDelegate();
private
void
Form1_Load(
object
sender, EventArgs e)
{
cbd = CallBack;
//設置回掉函數
}
private
void
Callback()
{
//能夠對主線程進行操做
}
private
void
MyTimmer(
object
obj)
{
try
{
while
(
true
)
{
Thread.Sleep(5000);
// 每次間隔的時間,本身設定
CallBackDelegate cbd = obj
as
CallBackDelegate;
this
.BeginInvoke(cbd);
//調用回掉。若是須要參數能夠加上參數
}
}
catch
{
}
}
有了如上代碼,在寫一個按鈕 做爲開始按鈕,觸發MyTimmer
private
void
button1_Click(
object
sender, EventArgs e)
{
t =
new
Thread(MyTimmer);
t.IsBackground =
true
;
t.Start(cbd);
}
using CodePayPro.Business;
using CodePayPro.Common;
using NSoup;
using NSoup.Nodes;
using NSoup.Select;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Utility;html
namespace CodePayPro.Auto
{
#region 參考資料
//SendMessage:https://blog.csdn.net/chen504390172/article/details/18525823
//
#endregion
public partial class Form1 : Form
{
/*
也就是說你並不能解決在子線程中去控制主窗體控件的問題。
這裏就須要委託。 定義一個 委託。加載以後給他綁定一個方法Callback,也就是所說的回掉函數。web
而後寫一個線程,線程須要一個object 的參數。將你定義的委託看成參數傳進線程中的方法。瀏覽器
在線程中去計時。作成一個while(true)的循環,循環內停十分鐘,函數
而後使用beiginInvoke調用委託,天然會觸發主線程中的callback方法。ui
在callback 方法內,因爲是主線程,你就能夠對你任意的控件進行操做了
*/this
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
public Form1()
{
InitializeComponent();
webBrowser1.Navigate("https://consumeprod.alipay.com/record/advanced.htm");
//註冊一個事件
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
this.webBrowser1.ScriptErrorsSuppressed = true;//就不會報腳本錯誤了
}url
Thread t = null;//建立線程,用來定時刷新數據。
//定義一個委託
public delegate void CallBackDelegate();
CallBackDelegate cbd = null;
private void Form1_Load_1(object sender, EventArgs e)
{
//加載以後給他綁定一個方法Callback,也就是所說的回掉函數。
cbd = CallBack;//設置回掉函數
}
//寫一個線程,線程須要一個object 的參數。將你定義的委託看成參數傳進線程中的方法。
private void MyTimmer(object obj)
{
try
{
while (true)
{
Thread.Sleep(10 * 1000);// 每次間隔的時間,本身設定
CallBackDelegate cbd = obj as CallBackDelegate;
this.BeginInvoke(cbd);//調用回掉。若是須要參數能夠加上參數
}
}
catch
{
}
}
/// <summary>
/// 回調函數
/// </summary>
private void CallBack()
{
//能夠對主線程進行操做
try
{
//webBrowser1.Navigate("https://consumeprod.alipay.com/record/advanced.htm");
//切換到帳號密碼登陸
HtmlElement ui_nav = webBrowser1.Document.GetElementById("J-loginMethod-tabs");
if (ui_nav != null)
{
ui_nav.Children[1].InvokeMember("click");
}
HtmlElement tbUserId = webBrowser1.Document.GetElementById("J-input-user");//帳號
HtmlElement tbPwd = webBrowser1.Document.GetElementById("password_rsainput");//密碼
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("J-login-btn");
if (tbUserId != null && tbPwd != null)
{
string payAccount = GetPayVal()[0];
string payPwd = GetPayVal()[1];
if (payAccount.IsNotNullOrEmpty() && payPwd.IsNotNullOrEmpty())
{
tbUserId.SetAttribute("value", payAccount);
tbPwd.SetAttribute("value", payPwd);
btnSubmit.Style = " position: fixed;z-index: inherit;top: 0px;left: 0px;";
if (MoNiclick())
{
btnSubmit.InvokeMember("click");
}
}
}
else
{
AddAlipayTradeData();
}
}
catch (Exception ex)
{
throw;
}
}
private void button1_Click(object sender, EventArgs e)
{
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("J-login-btn");
if (btnSubmit != null)
{
btnSubmit.Style = " position: fixed;z-index: inherit;top: 0px;left: 0px;";
MoNiclick();
btnSubmit.InvokeMember("click");
}
else
{
AddAlipayTradeData();//執行採集數據
}
//定時執行採集交易數據
t = new Thread(MyTimmer);
t.IsBackground = true;
t.Start(cbd);
}
//註冊一個事件,實現切換到帳密輸入的面板,而後輸入帳密
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
//切換到帳號密碼登陸
HtmlElement ui_nav = webBrowser1.Document.GetElementById("J-loginMethod-tabs");
ui_nav.Children[1].InvokeMember("click");
string strhtml = webBrowser1.Document.Body.InnerHtml;
HtmlElement tbUserId = webBrowser1.Document.GetElementById("J-input-user");//帳號
HtmlElement tbPwd = webBrowser1.Document.GetElementById("password_rsainput");//密碼
HtmlElement btnSubmit = webBrowser1.Document.GetElementById("J-login-btn");
if (tbUserId == null || tbPwd == null)
{
return;
}
//賦值
tbUserId.SetAttribute("value", "pingjumy1@pingjumy.com");
tbPwd.SetAttribute("value", "Zz1314520");
//tbUserId.SetAttribute("value", GetPayVal()[0]);
//tbPwd.SetAttribute("value", GetPayVal()[1]);
}
catch (Exception ex)
{
//throw;
}
}
/// <summary>
/// 獲取帳號密碼
/// </summary>
/// <returns></returns>
public List<string> GetPayVal()
{
string txtPath = ConfigurationManager.AppSettings["pay_path"];
string strValue = new CommonFunction().Read(txtPath);
return strValue.Split(',').ToList();
}spa
/// <summary>
/// 將元素定位到瀏覽器的左上角,這樣程序便快速的找到要點擊的元素。
/// </summary>
private bool MoNiclick()
{
int x = 0; // X coordinate of the click
int y = 0; // Y coordinate of the click
IntPtr handle = webBrowser1.Handle;
StringBuilder className = new StringBuilder(100);
while (className.ToString() != "Internet Explorer_Server") // The class control for the browser
{
handle = GetWindow(handle, 5); // Get a handle to the child window
GetClassName(handle, className, className.Capacity);
}
IntPtr lParam = (IntPtr)((y << 16) | x); // The coordinates
IntPtr wParam = IntPtr.Zero; // Additional parameters for the click (e.g. Ctrl)
const uint downCode = 0x201; // Left click down code
const uint upCode = 0x202; // Left click up code .net
SendMessage(handle, downCode, wParam, lParam); // Mouse button down
SendMessage(handle, upCode, wParam, lParam); // Mouse button up
return true;
}
#region 模擬百度點擊搜索
//相關連接:https://blog.csdn.net/yuanzhugen/article/details/40263213
//private void button1_Click(object sender, EventArgs e)
//{
// HtmlDocument doc = this.webBrowser1.Document;
// HtmlElement keyword = doc.GetElementById("kw");
// keyword.InnerText = "冰川時代";
// doc.GetElementById("su").InvokeMember("click");
//}
#endregion
/// <summary>
/// 定時執行採集交易數據
/// </summary>
//public void TimerClick()
//{
// #region 定時器事件 線程
// System.Timers.Timer aTimer = new System.Timers.Timer();
// aTimer.Elapsed += new ElapsedEventHandler(TimedEvent);
// aTimer.Interval = 10 * 1000; //配置文件中配置的秒數
// aTimer.Enabled = true;
// #endregion
//}
//private void TimedEvent(object sender, EventArgs e)
//{
// try
// {
// webBrowser1.Navigate("https://lab.alipay.com/consume/record/items.htm");
// HtmlElement btnSubmit = webBrowser1.Document.GetElementById("J-login-btn");
// if (btnSubmit != null)
// {
// btnSubmit.Style = " position: fixed;z-index: inherit;top: 0px;left: 0px;";
// MoNiclick();
// btnSubmit.InvokeMember("click");
// }
// else
// {
// AddAlipayTradeData();
// }
// }
// catch (Exception ex)
// {
// throw;
// }
//}
//模擬登錄---基本方法
//public bool SubmitAlipay()
//{
// webBrowser1.Navigate("https://lab.alipay.com/consume/record/items.htm");
// //切換到帳號密碼登陸
// HtmlElement ui_nav = webBrowser1.Document.GetElementById("J-loginMethod-tabs");
// ui_nav.Children[1].InvokeMember("click");
// string strhtml = webBrowser1.Document.Body.InnerHtml;
// HtmlElement tbUserId = webBrowser1.Document.GetElementById("J-input-user");//帳號
// HtmlElement tbPwd = webBrowser1.Document.GetElementById("password_rsainput");//密碼
// HtmlElement btnSubmit = webBrowser1.Document.GetElementById("J-login-btn");
// if (tbUserId == null || tbPwd == null)
// {
// return false;
// }
// //賦值
// tbUserId.SetAttribute("value", "qhtzkj@163.com");
// tbPwd.SetAttribute("value", "Clan1688");
// btnSubmit.InvokeMember("click");
// return true;
//}
private string GetWebClient(string url)
{
string strHTML = "";
WebClient myWebClient = new WebClient();
Stream myStream = myWebClient.OpenRead(url);
StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("GBK"));
strHTML = sr.ReadToEnd();
myStream.Close();
return strHTML;
}
/// <summary>
/// 採集支付寶交易數據
/// </summary>
/// <param name="strhtml"></param>
/// <returns></returns>
public Opresult AddAlipayTradeData()
{
try
{
HtmlElement searchBtn = webBrowser1.Document.GetElementById("J-set-query-form");//搜索查詢按鈕
searchBtn.InvokeMember("click");
//webBrowser1.Navigate("https://consumeprod.alipay.com/record/advanced.htm");
string strhtml = webBrowser1.Document.Body.InnerHtml;
int startIndex = strhtml.IndexOf("<table");
int endIndex = strhtml.IndexOf("</table>");
string tableHtml = strhtml.Substring(startIndex, endIndex + 8 - startIndex);
Document htmlDoc = NSoupClient.Parse(tableHtml);
Elements trEle = htmlDoc.GetElementsByTag("tbody");
List<Hashtable> hashList = new List<Hashtable>();
foreach (Element item in trEle)
{
foreach (var child in item.Children)
{
if (child.Children[0].ClassName() != "number")
{
break;
}
Hashtable hash = new Hashtable();
for (int i = 0; i < child.Children.Count; i++)
{
hash.Add(child.Children[i].ClassName(), child.Children[i].Text());
}
hashList.Add(hash);
}
}
string strJson = JsonExtend<List<Hashtable>>.ToJson(hashList);
if (hashList.Count > 0)
{
return new AlipayTradeDataBLL().AddRange(hashList);
}
}
catch (Exception ex)
{
return new Opresult() { errcode = -1, errmsg = ex.Message.ToString() };
}
return new Opresult() { errcode = -1, errmsg = "操做失敗,請稍後再試" };
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
} }}