当前位置: 移动技术网 > IT编程>开发语言>c# > C#之WinForm WebBrowser实用技巧汇总

C#之WinForm WebBrowser实用技巧汇总

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例汇总了c#中winform webbrowser常见的实用技巧,对于c#程序开发来说有不错的借鉴价值。分别叙述如下:

方法1:获取状态栏信息

void webbrowser1_statustextchanged(object sender, eventargs e)
{
  label1.text = webbrowser1.statustext;
}

方法2:页面跳转后改变地址栏地址

//在navigated事件处理函数中改变地址栏地址是最恰当的:
private void webbrowser1_navigated(object sender, webbrowsernavigatedeventargs e)
{
  textbox1.text = webbrowser1.url.tostring();
}

方法3:设置单选框

//建议使用执行单击事件的方式来设置单选框,而不是修改属性:
webbrowser1.document.getelementbyid("rbt_a").invokemember("click");

方法4:设置联动型下拉列表

//比较常见的联动型多级下拉列表就是省/市县选择了,这种情况下直接设置选择项的属性不会触发联动,需要在最后执行触发事件函数才能正常工作:

foreach (htmlelement f in s.getelementsbytagname("option"))
{
  if (f.innertext == "北京")
  {
    f.setattribute("selected", "selected");
  }
  else
  {
    f.setattribute("selected", "");
  }
}
s.raiseevent("onchange");

方法5:在winform中响应web事件

假设html源代码如下:

<html> 
<body> 
<input type="button" id="btnclose" value="关闭" /> 
</body> 
</html>

htmldocument htmldoc = webbrowser.document; 
htmlelement btnelement = htmldoc.all["btnclose"]; 
if (btnelement != null) 
{ 
  btnelement.click += new htmlelementeventhandler(htmlbtnclose_click); 
}

很简单吧?那么稍稍高级一点的——我们都知道一个html元素可能有很多各种各样的事件,而htmlelement这个类只给出最常用、共通的几个。那么,如何响应其他事件呢?这也很简单,只需要调用htmlelement的attacheventhandler就可以了:

btnelement.attacheventhandler("onclick", new eventhandler(htmlbtnclose_click)); 

这一句等价于上面的btnelement.click += new htmlelementeventhandler(htmlbtnclose_click);

对于其他事件,把"onclick"换成该事件的名字就可以了。例如:

formelement.attacheventhandler("onsubmit", new eventhandler(htmlform_submit)); 

 
方法6:模拟表单自动填写和提交

假设有一个最简单的登录页面,输入用户名密码,点“登录”按钮即可登录。已知用户名输入框的id(或name,下同)是username,密码输入框的id是password,“登录”按钮的id是submitbutton,那么我们只需要在webbrowser的documentcompleted事件中使用下面的代码即可:

htmlelement btnsubmit = webbrowser.document.all["submitbutton"]; 
htmlelement tbuserid = webbrowser.document.all["username"]; 
htmlelement tbpasswd = webbrowser.document.all["password"]; 

if (tbuserid == null || tbpasswd == null || btnsubmit == null) 
  return; 

tbuserid.setattribute("value", "smalldust"); 
tbpasswd.setattribute("value", "12345678"); 

btnsubmit.invokemember("click");

关于表单的提交,的确还有另一种方法就是获取form元素而不是button,并用form元素的submit方法:

htmlelement formlogin = webbrowser.document.forms["loginform"]; 
//…… 
formlogin.invokemember("submit"); 

本文之所以没有推荐这种方法,是因为现在的网页,很多都在submit按钮上添加onclick事件,以对提交的内容做最基本的验证。如果直接使用form的submit方法,这些验证代码就得不到执行,有可能会引起错误。

方法7:调用脚本

首先是调用web页面的脚本中已经定义好的函数。假设html中有如下javascript:

function doadd(a, b) {
  return a + b;
}

那么,我们要在winform调用它,只需如下代码即可:

object osum = webbrowser.document.invokescript("doadd", new object[] { 1, 2 });
int sum = convert.toint32(osum);

其次,如果我们想执行一段web页面中原本没有的脚本,该怎么做呢?这次.net的类没有提供,看来还要依靠com了。ihtmlwindow2可以将任意的字符串作为脚本代码来执行。

string scriptline01 = @"function showpageinfo() {";
string scriptline02 = @"   var numlinks = document.links.length; ";
string scriptline03 = @"   var numforms = document.forms.length; ";
string scriptline04 = @"   var numimages = document.images.length; ";
string scriptline05 = @"   var numscripts = document.scripts.length; ";
string scriptline06 = @"   alert('网页的统计结果:\r\n链接数:' + numlinks + ";
string scriptline07 = @"    '\r\n表单数:' + numforms + ";
string scriptline08 = @"    '\r\n图像数:' + numimages + ";
string scriptline09 = @"    '\r\n脚本数:' + numscripts);}";
string scriptline10 = @"showpageinfo();";

string strscript = scriptline01 + scriptline02 + scriptline03 + scriptline04 + scriptline05 +
          scriptline06 + scriptline07 + scriptline08 + scriptline09 + scriptline10;

ihtmlwindow2 win = (ihtmlwindow2)webbrowser.document.window.domwindow;
win.execscript(strscript, "javascript");

最后:在脚本中调用winform里的代码,这个可能吗? 呵呵,当然是可能的。
下面的代码示例演示如何使用 objectforscripting 属性。在该示例中,objectforscripting 属性被设置为当前窗体。

using system;
using system.windows.forms;
using system.security.permissions;
 
[permissionset(securityaction.demand, name="fulltrust")]
[system.runtime.interopservices.comvisibleattribute(true)]
public class form1 : form
{
  private webbrowser webbrowser1 = new webbrowser();
  private button button1 = new button();
 
  [stathread]
  public static void main()
  {
    application.enablevisualstyles();
    application.run(new form1());
  }
 
  public form1()
  {
    button1.text = "call script code from client code";
    button1.dock = dockstyle.top;
    button1.click += new eventhandler(button1_click);
    webbrowser1.dock = dockstyle.fill;
    controls.add(webbrowser1);
    controls.add(button1);
    load += new eventhandler(form1_load);
  }
 
  private void form1_load(object sender, eventargs e)
  {
    webbrowser1.allowwebbrowserdrop = false;
    webbrowser1.iswebbrowsercontextmenuenabled = false;
    webbrowser1.webbrowsershortcutsenabled = false;
    webbrowser1.objectforscripting = this;
    // uncomment the following line when you are finished debugging.
    //webbrowser1.scripterrorssuppressed = true;
 
    webbrowser1.documenttext =
      "<html><head><script>" +
      "function test(message) { alert(message); }" +
      "</script></head><body><button " +
      "onclick=\"window.external.test('called from script code')\">" +
      "call client code from script code</button>" +
      "</body></html>";
  }
 
  public void test(string message)
  {
    messagebox.show(message, "client code");
  }
 
  private void button1_click(object sender, eventargs e)
  {
    webbrowser1.document.invokescript("test",
      new string[] { "called from client code" });
  }
 
}
//该代码实例源于:msdn

相信本文所述实例对大家的c#程序设计有一定的借鉴价值。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网