让自定义Prompt窗体中在BackgroundWorker中使用COM组件WebBrowser

本文介绍了一个名为PromptWindow的功能实现,该实现主要用于显示提示信息并获取WebBrowser控件中的Cookie信息。通过创建一个窗体并设置必要的控件,如TextBox和Button,实现了与用户的交互。此外,还提供了一种在BackgroundWorker中使用该功能的方法。

Prompt Window的实现:

public static class Prompt { public static string ShowDialog(string defaultext, string text, string caption) { Thread.CurrentThread.SetApartmentState(ApartmentState.STA); // SAMPLE TEXT // WAT-Analyzer has encountered 503 error when access the following URL. // Please open below URL with your IE browser, and complete the "" manually. // Then click the OK button to continue. http://www.google.com/search?q=xxx&s //Form prompt = new Form() { Width = 500, Height = 150, Text = caption, FormBorderStyle = FormBorderStyle.FixedToolWindow }; Form prompt = new Form() { Width = 500, Height = 470, Text = caption}; //prompt.Width = 500; //prompt.Height = 150; //prompt.Text = caption; TextBox textLabel = new TextBox() { Left = 50, Top = 20, Width = 400, Height = 50, Text = text, Multiline = true, ReadOnly = true, BackColor = Color.FromName("Control"), BorderStyle = BorderStyle.None, TabStop = false }; TextBox textBox = new TextBox() { Left = 50, Top = 70, Width = 400, Text = "Paste the cookies that can be got from software Wireshark" }; Button confirmation = new Button() { Text = "OK", Left = 350, Width = 100, Top = 90 }; confirmation.Click += (sender, e) => { prompt.Close(); }; prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.Controls.Add(textBox); textBox.SelectAll(); ////////////////////////////////// WebBrowser wb = new WebBrowser() { Top = 100, Left = 50, Width = 400, Height = 300 }; prompt.Controls.Add(wb); wb.Navigate(defaultext); confirmation.Top = 410; ////////////////////////////////// prompt.ShowDialog(); return wb.Document.Cookie; //return textBox.Text; } }

解释:

从实现的第一行线程的代码可以看出,Prompt运行的内容所在的线程需要使用STA模式,如果开发时不使用像WebBrowser这样的COM的话,可以忽略这行代码,关于STA与MTA的解释在这里(http://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta)可以找到。重点核心的代码就是prompt.ShowDialog()以及它下面的一行,ShowDialog会显示窗体,代码停留在这里直到窗体被关闭。当窗体关闭时,可以把窗体内的文本返回,而这里所返回的是浏览器的Cookie信息。

让WebBrowser在BackgroudWorker中工作:

Thread t = new Thread(delegate() { cookie = Prompt.ShowDialog(url, spec, "Warning Message"); }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join();

解释:

假设上面的代码在BackgroundWorker中运行,时不时地就会有异常发生,原因是BackgroundWorker本身的线程模式不是STA。所以需要从当前位置新开启一个STA模式的,为了让代码暂时停留直到窗体关闭,用Join进行阻塞。Thread构造函数中所使用的是匿名访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值