入门C#应用WebBrowser与web页面交互
下面讲一下.NET中使用WebBrowser(winform)的交互应用。
一、在项目中加入WebBrowser控件,并load事件中绑定到相应网站,这里我以校内网的登录介面为例:
webBrowser1.Url = new Uri("http://www.renren.com/SysHome.do");
这样当你运行程序就会定位到校内网的登录页面;
二、winform与web页面的交互:
进入校内登录页面后,接下来我们来完成在winform程序中登录校内个人主页。查看校内的登录页面的源文件我们会发现:

<form method="post" id="loginForm" class="login-form" action="http://www.renren.com/PLogin.do" > <p class="top"> <label for="email">帐号:</label> <input type="text" name="email" class="input-text" id="email" tabindex="1" value=""/> </p> <p> <label for="password">密码:</label> <input type="password" id="password" name="password" error="请输入密码" class="input-text" tabindex="2" /> </p> <div class="caps-lock-tips" id="capsLockMessage" style="display:none"></div> <p> <label title="为了确保您的信息安全,请不要在网吧或者公共机房勾选此项!" class="labelCheckbox"> <input type="checkbox" name="autoLogin" id="autoLogin" value="true" tabindex="3" />下次自动登录 </label> </p> <p class="bottom"> <a class="float-right" href="http://safe.renren.com/findPass.do">找回密码</a><input type="hidden" name="origURL" value="http://www.renren.com/Home.do" /> <input type="hidden" name="domain" value="renren.com" /> <input type="submit" id="login" class="input-submit" value="登录" tabindex="4" /> </p> </form>
我们要做的就是取得<form>内的而要我们填充登录信息的元素:我们看到上面有"账号:"它对应的就是我们登录校内时的个人账户:我们要做的就是在<input>中写入我们的账户,不过首先我们要获取这个元素以便对它赋值:而.net 也给我们提供了这个方法:
HtmlElement name = webBrowser1.Document.All["email"];
HtmlElement对象,All["这里要填写的就是网页中文本输入框的id或name"];
接下来我们就可以为账户赋值了:
name.SetAttribute("value", txtname.Text.ToString());
其中txtname.Text.ToString()就是校内账户,同样密码也是同样;
接下来就是登录了可以看一下登录按钮:
<input type="submit" id="login" class="input-submit" value="登录" tabindex="4" />
它的获取同上,如何执行这个事件:
btnsubmit.InvokeMember("click");
其中btnsubmit是和name一样的HtmlElement对象。上而这句就完成了按钮的单击事件;简单的winform登录web页面就完成了,下面是完整的代码:

HtmlElement name = webBrowser1.Document.All["email"]; HtmlElement pwd = webBrowser1.Document.All["password"]; HtmlElement formlogin = webBrowser1.Document.Forms["loginForm"]; if (formlogin == null || name == null || pwd == null) { MessageBox.Show("页面读取出错!"); return; } name.SetAttribute("value", txtname.Text.ToString()); pwd.SetAttribute("value", txtpwd.Text.ToString()); btnsubmit.InvokeMember("click");
就这么简单。
推荐文章:
原创:.NET中winform与webform互相通讯实例,CS调用BS页面的JS函数
热门标签
赞助商链接
@CopyRight 2002-2008, 1SOHU.COM, Inc. All Rights Reserved QQ:1010969229