简体   繁体   English

在C#中禁用编辑WebBrowser

[英]Disable Editing WebBrowser in C#

So I've been working on this project, and we have a WebBrowser object on the form. 因此,我一直在从事这个项目,并且表单上有一个WebBrowser对象。 The purpose of the object is that it loads in HTML Forms into it to be viewed, at this current point in time though, you are able to edit the contents of the HTML form, which is not desired. 该对象的目的是将其加载到HTML表单中以供查看,但是在当前时间点,您可以编辑HTML表单的内容,这是不需要的。

I want to simply display this HTML form of information to the user, but not allow them to alter the textboxes or checkboxes or anything of that nature on the form. 我只想向用户显示此HTML形式的信息,但不允许他们更改文本框或复选框或表单上任何具有这种性质的内容。

I tried using the Navigating event and set e.cancel = true;. 我尝试使用导航事件并设置e.cancel = true;。 This haulted the control from even loading the page. 这使控件无法加载页面。 And if I set it to only execute e.cancel = true; 如果我将其设置为仅执行e.cancel = true; after the form had loaded, I could still change text boxes and such on the form, as it only seemed to randomly called the Navigating event. 加载表单后,我仍然可以更改文本框等表单,因为它似乎只是随机调用了Navigating事件。

Does anyone know of a way to get a WebBrowser object to be read only? 有谁知道一种使WebBrowser对象为只读的方法吗?

Cheers! 干杯!

You could try accessing all form elements on the page and set the readonly attribute on the tag. 您可以尝试访问页面上的所有表单元素,并在标签上设置readonly属性。 Something like: 就像是:

var inputs = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement element in inputs)
{
  element.SetAttribute("readonly", "readonly");
}

You'd obviously have to repeat the process for all form elements (select etc.), but it should work. 您显然必须对所有表单元素(选择等)重复此过程,但是它应该可以工作。

You can apply contentEditable attribute to the Body tag of the document. 您可以将contentEditable属性应用于文档的Body标签。

Document.Body.SetAttribute("contentEditable", false);

This will make your document readonly for user. 这将使您的文档对用户只读。

I have been running into this issue as well. 我也一直在遇到这个问题。 Thanks to steavy I have been able to come up with a solution : 多亏了steavy,我得以提出一个解决方案:

Hook up to the DocumentCompleted event (you can do this in the designer) : 连接到DocumentCompleted事件(您可以在设计器中执行此操作):

myWebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_procedure_DocumentCompleted);

Then make it readonly in the event : 然后在事件中将其设置为只读:

private void myWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    myWebBrowser.Document.Body.SetAttribute("contentEditable", "false");
}

I do this in the event when the document is fully loaded because I sometimes ran into a NullReferenceException , the body wasn't loaded yet and the line would throw. 我会在文档完全加载的情况下执行此操作,因为有时我会遇到NullReferenceException ,但正文尚未加载,并且该行会抛出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM