How do I make the Delete key work in the WebBrowse

2019-08-31 09:01发布

问题:

I have a .net Windows forms project that includes the System.Windows.forms.WebBrowser control to allow the user to do some editing of HTML content. When this control is in edit mode Elements such as div or span can be drag-and-drop edited, but selecting an element and typing Delete does nothing.

I have seen a few posts that talk about making this work in C++ but they are not very detailed. Example http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/1f485dc6-e8b2-4da7-983f-ca431f96021f/

This next post talks about using a function called TranslateAccelerator method to solve similar problems in MFC projects. http://vbyte.com/iReader/Reader.asp?ISBN=0735607818&URI=/HTML/chaab.htm

Does anyone have a suggestion on how to make the delete key work in C# or VB for a windows forms project?

Here is my code to create the WebBrowser content:

WebBrowser1.Navigate("about:blank")   ' Initializes the control
Application.DoEvents
WebBrowser1.Document.OpenNew(False).Write("<html><body><span>Project Title</span><input type='text' value='' /></body></html>")
WebBrowser1.ActiveXInstance.Document.DesignMode = "On"  ' Option Explicit must be set to off
WebBrowser1.Document.Body.SetAttribute("contenteditable", "true")

Thanks

回答1:

Well the problem was that one of the control properties, "WebBrowserShortcutsEnabled" was set to false. Thanks everyone for your help, there is no way anyone could have guessed that so I get a big "DUH!". I did find a way to make this work in c# where the code would look like this:

public Form1() {
    InitializeComponent();
    webBrowser1.Navigate("about:blank");  // Initializes the webbrowser control
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
    mshtml.IHTMLDocument2 doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
    doc.designMode = "On";
    webBrowser1.Document.OpenNew(false).Write(@"<html><body><span>Project Title</span><input type=""text"" value="""" /></body></html>");
}

...assuming that a reference had been added to MSHTML. The documentCompleted event accomplishes the same thing as the Application.DoEvents in my first code exmaple, so that could go either way.



回答2:

I just tried this method:

webBrowser1.Navigate(@"javascript:document.body.contentEditable='true'; document.designMode='on'; void 0");

Elements can be dragged and deleted, you can also edit text with a double click.