WebBrowser 多线程 DocumentCompleted 和定时器

时间:2022-04-15 23:54:18

 

备忘

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Fizzler;
using Fizzler.Systems;
using Fizzler.Systems.HtmlAgilityPack;
using Fizzler.Systems.XmlNodeQuery; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Uri url = new Uri("http://www.c-sharpcorner.com/forums/Search/?forum=0&searchtype=0&searchtext=");
runBrowserThread(url);
} static private void runBrowserThread(Uri url)
{
var th = new Thread(() =>
{
var br = new WebBrowser();
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate(url); TimerCallback timerDelegate = new TimerCallback(CheckStatus);
//System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(timerDelegate, br.DocumentText, 1000, 1000);
System.Windows.Forms.Timer timers = new System.Windows.Forms.Timer();
timers.Enabled = true;
timers.Interval = 1000;
timers.Tick += delegate(object o, EventArgs args)
{
CheckStatus(br.DocumentText);
};
timers.Start();
Application.Run();
//Application.DoEvents(); });
th.SetApartmentState(ApartmentState.STA);
th.Start();
} static void CheckStatus(Object state)
{ try
{ string html = state.ToString(); // Console.WriteLine(html);
if (checklistbape(html))
{
//这里主要用来进行ajax检测
//检测成功后,对内容进行处理
//定时器对页面状态进行轮训和判断进行那个操作
Console.WriteLine("OK"); // Application.ExitThread(); // Stops the thread
}
else
{
Console.WriteLine("= =");
}
}
catch (Exception ex)
{
string ss = "";
}
}
private static bool checklistbape(string htmltext)
{
var html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(htmltext);
var document = html.DocumentNode;
var urlnode = document.QuerySelectorAll(".latestArticle>li").ToList();
var next = document.QuerySelectorAll(".pagingSpritIcons").ToList();
if (urlnode.Count == 0 || next.Count == 0)
{
return false;
}
else
{
return true;
}
}
static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br = sender as WebBrowser;
if (br.Url == e.Url)
{
Console.WriteLine("Natigated to {0}", e.Url);
// Application.ExitThread(); // Stops the thread
}
} }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }