简体   繁体   中英

Disable Editing WebBrowser in C#

So I've been working on this project, and we have a WebBrowser object on the form. 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.

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.

I tried using the Navigating event and set e.cancel = true;. This haulted the control from even loading the page. And if I set it to only execute 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.

Does anyone know of a way to get a WebBrowser object to be read only?

Cheers!

You could try accessing all form elements on the page and set the readonly attribute on the tag. 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.

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 :

Hook up to the DocumentCompleted event (you can do this in the designer) :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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