Code in bold green is the newly added code required for the context menu strip to work correctly. Since the text in this description box does not show font coloring or style I have attached the code as well. I believe I have copied all the code needed however if there are any problems please feel free to let me know.
The code below can be used by setting the context menu in the MouseDown event handler or in the designer code or I suppose anywhere necessary however I use the MouseDown event handler. One downfall is that when the user right clicks the control does not obtain focus, in my development environment this is not currently a big deal however eventually I'm sure I will get the request to fix it.
## Control Class ##
public class Control: Component
{
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
private ContextMenuOverride _cmo = null;
private ContextMenuStrip _ContextMenuStrip;
public ContextMenuStrip ContextMenuStrip
{
get { return _ContextMenuStrip; }
set
{
_ContextMenuStrip = value;
_cmo.ContextMenuStrip = _ContextMenuStrip;
}
}
private void _CreateControl( /*bool fIgnoreVisible*/ )
{
if( this.Created )
return;
if( !this.Visible )
return;
_cmo = new ContextMenuOverride(this);
//*** etc etc
}
protected virtual void OnMouseEnter( EventArgs e )
{
_cmo = new ContextMenuOverride(this);
_cmo.ContextMenuStrip = _ContextMenuStrip;
if( MouseEnter != null )
MouseEnter(this,e);
}
protected virtual void OnMouseLeave( EventArgs e )
{
_cmo.Dispose();
_cmo = null;
if( MouseLeave != null )
MouseLeave(this,e);
}
public System.Drawing.Point MouseLocationInControl = MousePosition;
public event MouseEventHandler MouseMove;
protected virtual void OnMouseMove( MouseEventArgs e )
{
MouseLocationInControl = e.Location;
if( MouseMove != null )
MouseMove(this,e);
}
}
## ContextMenuOverride Class ##
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
namespace System.Windows.Forms
{
internal class ContextMenuOverride
{
private Control _field;
public ContextMenuStrip ContextMenuStrip;
public ContextMenuOverride(Control field)
{
_field = field;
HtmlPage.Document.AttachEvent("oncontextmenu", this.OnContextMenu);
}
public void Dispose()
{
HtmlPage.Document.DetachEvent("oncontextmenu", this.OnContextMenu);
}
private void OnContextMenu(object sender, HtmlEventArgs e)
{
e.PreventDefault();
if (ContextMenuStrip != null)
ContextMenuStrip.Show(_field, _field.MouseLocationInControl);
}
}
}
Nick Hanshaw
Control ContextMenuStrip