1 March 2007

Cut/Copy/Paste for the .Net Windows Forms Web Browser Control

Posted by Mikhail Esteves under: C#; Tips .

Implementing custom Cut/Copy/Paste functionality with the .NET Web Browser control is quite easy to achieve. Here is how:

Sample WebBrowser Context Menu

First, add a reference to Microsoft.mshtml. Then:

using mshtml;

private bool IsCommandEnabled(string wCmd)
{
  IHTMLDocument2 doc2 = tBrowser.Document.DomDocument
    as IHTMLDocument2;
  if (doc2 != null)
    return doc2.queryCommandEnabled(wCmd);
  return false;
}

private void UpdateButtons()
{
  // Button states are handled here.
  ctxMenuCut.Enabled = IsCommandEnabled("Cut");
  ctxMenuCopy.Enabled = IsCommandEnabled("Copy");
  ctxMenuPaste.Enabled = IsCommandEnabled("Paste");
}

Next, assign CtxMenuClickHandler as the Click Event Handler for all the Cut/Copy/Paste buttons.

private void CtxMenuClickHandler(object sender, EventArgs e)
{
  if (sender == ctxMenuCut)
  {
    tBrowser.Document.ExecCommand("Cut", false, null);
    UpdateButtons();
  }
  else if (sender == ctxMenuCopy)
  {
    tBrowser.Document.ExecCommand("Copy", false, null);
    UpdateButtons();
  }
  else if (sender == ctxMenuPaste)
  {
    tBrowser.Document.ExecCommand("Paste", false, null);
    UpdateButtons();
  }
}

Now, disable the Web Browser component’s default context menu by setting the IsWebBrowserContextMenuEnabled to false. Attach a custom ContextMenu to it, and add an Opening event handler that calls UpdateButtons:

private void tBrowserContextMenu_Opening(object sender, CancelEventArgs e)
{
  UpdateButtons();
}

You could also use IsCommandEnabled with SelectAll, Undo and Redo options.



One Comment so far...

Vassilios Says:

9 September 2007 at 7:59 am.

Nice!

Leave a Reply

Browse

Photography

Projects

Pages

Calendar

March 2007
M T W T F S S
« Feb   Apr »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

www.flickr.com

Use OpenDNS