F# -- WebBroswer 控件测试

今天熟悉了下F# 中使用WebBroswer控件, 代码如下:

// Learn more about F# at http://fsharp.net
// See the 'F# Tutorial' project for more help.
open System.Windows.Forms
open System
open System.Xml
open System.Net
open System.Web
open HtmlAgilityPack
open System.IO

let asyncGrapUrl(newUrl : string) =
    async{            
        let fileNameXml = @"D:\" + newUrl.Replace('.','0').Replace('/','0').Replace(':','0') + ".xml"       

        if(File.Exists(fileNameXml)) then
            File.Delete(fileNameXml)
                    
        let httpRequest = HttpWebRequest.Create(newUrl) :?> HttpWebRequest
        let! httpRespon = Async.AwaitTask(httpRequest.GetResponseAsync())
        let responStream = httpRespon.GetResponseStream()
        
        let xml = new HtmlDocument()
        xml.Load(responStream,Text.Encoding.GetEncoding("gb2312"),true)
        xml.OptionOutputAsXml <- true
        xml.Save(fileNameXml)
        let htmlTxt = xml.DocumentNode
        let htmlSrc = htmlTxt.InnerHtml        
        let htmlSrcWithoutImage = 
            let strDelImg = System.Text.RegularExpressions.Regex.Replace(htmlSrc,@"<img.*/>",@"<br/>")
            let strDelScript = System.Text.RegularExpressions.Regex.Replace(strDelImg,@"<script",@"<!--<script")
            let mutable str = System.Text.RegularExpressions.Regex.Replace(strDelScript,@"</script>",@"</script>-->")
            str <- System.Text.RegularExpressions.Regex.Replace(str,@"</head>",@"</head>-->")
            str <- System.Text.RegularExpressions.Regex.Replace(str,@"<head",@"<!--<head")
            str
//            str <- System.Text.RegularExpressions.Regex.Replace(str,@"<form",@"<!--<form")
//            System.Text.RegularExpressions.Regex.Replace(str,@"</form>",@"</form>-->")
        responStream.Close()
        return htmlSrcWithoutImage
    } |> Async.RunSynchronously



let createBrowser(url : string) =
    let form = new Form()
    form.Text <- "Test"
    let broswer = new System.Windows.Forms.WebBrowser()
    let html = asyncGrapUrl(url)    
    broswer.DocumentText <- html
    broswer.AutoSize <- true
    broswer.Dock <- DockStyle.Fill
    broswer.AllowNavigation <- true
    
    
    
    form.Controls.Add(broswer)
    printfn "Hi"
    form.Show()
    Application.Run(form)
    
let url = @"http://www.news.baidu.com" 
let thread = new System.Threading.Thread(new Threading.ParameterizedThreadStart(fun _ -> createBrowser(url)))
thread.SetApartmentState(Threading.ApartmentState.STA)

thread.Start()



[<EntryPoint>]
let main argv = 
    //do Application.Run(form)
    printfn "%A" argv
    0 // return an integer exit code

笔记~
需要注意的是: thread.SetApartmentState(Threading.ApartmentState.STA), 如果没有这样的设置,将会出现 : ActiveX control cannot be instantiated because the current thread is not in a single-threaded apartment. 这样的错误。

posted @ 2013-01-10 19:39  ZackZhou  阅读(227)  评论(0编辑  收藏  举报