第一步:创建Form窗体,添加以下控件实现页面基本的布局
webBrowser1控件设置Dock属性为Fill之后,会铺满下面整个panel2
第二步:添加下面代码,主要是点击的时候获取输入的url地址,并将地址赋值给webBrowser1控件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Home
{
// 这个是测试用的 --
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
button1.Click += Button1_Click;
textBox1.KeyUp += textBox1_KeyUp; //键盘事件
}
public void textBox1_KeyUp(object sender, KeyEventArgs e)
{
//MessageBox.Show("进来了");
if (e.KeyCode == Keys.Enter) //判断是否是Enter按键
{
e.Handled = true;
this.Button1_Click(sender, e);
}
}
public void Button1_Click(object sender, EventArgs e)
{
string pattern = @"^www\..+\.com$";
Regex regex = new Regex(pattern);
bool isUrl = regex.IsMatch(textBox1.Text); //判断正则是否符合
if(isUrl)
{
Uri uri = new Uri("https://" + textBox1.Text); //字符串装成url要遵循http的协议
webBrowser1.Url = uri;
}
else{
if (textBox1.Text == "" || textBox1.Text ==null)
{
return;
}
MessageBox.Show("您好输入的url格式有误,请重新输入");
textBox1.Text = "";
}
}
//webBrowser1.ScriptErrorsSuppressed = true;
//设置控件的这个属性为true , 就可以解决脚本报错的问题
}
}
这边有几个地方需要注意:
1. 初始化加载的时候会提示脚本报错的问题,可以通过设置webBrowser1.ScriptErrorsSuppressed = true; //设置控件的这个属性为true , 就可以解决脚本报错的问题
2.输入的String格式的地址,要符合new Url();出来的实例要求,需要加上http 或 https协议,上面案例手动添加的,后面根据功能,自己调整格式
第三步:运行,输入url地址,点击跳转或者按键盘Enter键
涉及到的知识点:
1.正则判断
string pattern = @"^www\..+\.com$";
Regex regex = new Regex(pattern);
bool isUrl = regex.IsMatch(textBox1.Text); //判断正则是否符合
2.格式转换
Uri uri = new Uri("https://" + textBox1.Text); //字符串装成url要遵循http的协议
webBrowser1.Url = uri;
3.初始化脚本报错
//webBrowser1.ScriptErrorsSuppressed = true;
//设置控件的这个属性为true , 就可以解决脚本报错的问题
4.键盘触发事件
textBox1.KeyUp += textBox1_KeyUp; //键盘事件
public void textBox1_KeyUp(object sender, KeyEventArgs e)
{
//MessageBox.Show("进来了");
if (e.KeyCode == Keys.Enter) //判断是否是Enter按键
{
e.Handled = true;
this.Button1_Click(sender, e);
}
}
好了,今天分享的内容就到这里,操作也比较简单,感兴趣的码兄都可以试试,祝大家成功嵌套web页面。