我正在管理各种联系信息 - 电话、地址、电子邮件、IM 等,我希望它看起来不错并节省空间,所以我想在 WebBrowser 控件中显示它。我可以将标记和内容动态地创建到一个流中,并以任何格式显示它,并且可以轻松调整颜色和字体大小。我也可以放按钮 <input>
用于添加、编辑和删除。我喜欢这种方法,因为它看起来比 RichTextBox 更简单、更好看(如果您不这么认为,请纠正我。)
问题是关于响应这些按钮。如果选择了一个,我想隐藏 WebBrowser 并取消隐藏带有允许输入新联系人或编辑现有联系人所需的 TextBox 控件的面板。我听说这可以做到。我希望得到建议。我能想到的就是一些代码来获取 AJAX 调用,这会引发 Windows 事件,但这似乎......很奇怪。
任何想法、链接或建议都将不胜感激……甚至是不这样做的充分理由,但这似乎是高质量信息呈现的好主意,而且我已经动态生成了大量 html。
最佳答案
您可以使用 JavaScript 操作 Form
和 Controls
或从 WebBrowser
调用 C# 方法,也可以操作 WebBrowser 的内容
从 C# 控制或调用 JavaScript 方法。
从 Html 操作 WinForms
要从 WebBrowser
控件操作您的 Form
并调用 C# 方法并访问您的表单属性,您应该使用 [ComVisibleAttribute(true)]
装饰您的表单那么你可以将表单设置为ObjectForScripting
WebBrowser
控件的属性。
[ComVisibleAttribute(true)]
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.ObjectForScripting = this;
}
}
然后您可以简单地调用方法并以这种方式访问窗口元素:
从 JavaScript 调用 C# 方法:
window.external.SomeCSMethod('Method called from JavaScript');
从 JavaScript 设置 WinForms 控件的值:
通过将 Modifier
属性的值设置为 public
,使 Form
上的 textBox1
控件公开使用设计师。然后可以从 JavaScript 访问它:
window.external.textBox1.Text='Value set from JavaScript';
从 WinForms 操作 Html
您可以从 C# 代码操作 web 浏览器控件的 html 内容并调用 JavaScript 方法或使用 Document
的方法设置 html 元素的值WebBrowser
控件的属性:
从 C# 调用 JavaScript 方法:
this.webBrowser1.Document.InvokeScript("someJSMethod", new []{"Method called from C#"});
从 C# 设置 Html 控件的值:
this.webBrowser1.Document.GetElementById("text1")
.SetAttribute("Value set from C#", "Value From C#");
示例代码:
您可以创建一个 Form1
类并放置 button1
和 button2
以及 textBox1
和 webBrowser1
在您的 Form
上将 textBox1
的 Modifer
设置为 public:
[ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
button1.Click += button1_Click;
button2.Click += button2_Click;
}
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.DocumentText =
@"<html>
<head>
<title>Test</title>
<script>
function someJSMethod(value){alert(value);}
</script>
</head>
<body>
<input type=""text"" id=""text1""/>
<br/>
<input type=""button"" value=""Call C# Method"" id=""button1""
onclick=""window.external.SomeCSMethod('Method called from JavaScript');""/>
<br/>
<input type=""button"" value=""Set WinForms Control Value"" id=""button2""
onclick=""window.external.textBox1.Text='Value set from JavaScript';""/>
</body>
</html>";
this.webBrowser1.ObjectForScripting = this;
}
public void SomeCSMethod(string value)
{
MessageBox.Show(value);
}
private void button1_Click(object sender, EventArgs e)
{
this.webBrowser1.Document
.InvokeScript("someJSMethod", new[]{ "Method called from C#" });
}
private void button2_Click(object sender, EventArgs e)
{
this.webBrowser1.Document.GetElementById("text1")
.SetAttribute("value", "Value set from C#");
}
}
关于c# - WebBrowser 控件与 Windows 窗体之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834774/