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:

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.