Applies to: Nevron Diagram for .NET
How to change the Context Menu Strip when right-click at shape or a drawing view?
Sometimes your program logic may require to display a personalized context menu when the user right clicks on a specific shape. To achieve this you should subscribe to the drawing view's
MouseDown event and update the value
ContextMenu property of the drawing view if the specific shape was clicked or set it to
null or another context menu if it was not. The following is a simple example:
[C#]
NBasicShapesFactory factory =
new
NBasicShapesFactory();
factory.DefaultSize =
new
NSizeF(100, 100);
NShape shape = factory.CreateShape(BasicShapes.Rectangle);
shape.Location =
new
NPointF(100, 100);
document.ActiveLayer.AddChild(shape);
view.MouseDown += OnViewMouseDown;
[VB.NET]
Dim
factory
As
NBasicShapesFactory =
New
NBasicShapesFactory()
factory.DefaultSize =
New
NSizeF(100, 100)
Dim
shape
As
NShape = factory.CreateShape(BasicShapes.Rectangle)
shape.Location =
New
NPointF(100, 100)
document.ActiveLayer.AddChild(shape)
AddHandler
view.MouseDown,
AddressOf
OnViewMouseDown
Here's the code you need in the event handler:
[C#]
private
void
OnViewMouseDown(
object
sender, MouseEventArgs e)
{
// Make sure the right mouse button was clicked
if
(e.Button != MouseButtons.Right)
return
;
// Hit test the drawing document
NPointF location =
new
NPointF(e.Location);
NNodeList shapes = view.Document.HitTest(location, -1, NFilters.Shape2D, view.ProvideDocumentHitTestContext());
if
(shapes.Count == 0)
{
// No shape were found under the mouse cursor, so set the context
// menu of the view to null and return
view.ContextMenu =
null
;
return
;
}
// Create a context menu
ContextMenu contextMenu =
new
ContextMenu(
new
MenuItem[]{
new
MenuItem(
"Menu Item 1"
),
new
MenuItem(
"Menu Item 2"
),
new
MenuItem(
"-"
),
new
MenuItem(
"Menu Item 3"
)
});
// Set the context menu of the drawing view
view.ContextMenu = contextMenu;
}
[VB.NET]
Private
Sub
OnViewMouseDown(
ByVal
sender
As
Object
,
ByVal
e
As
MouseEventArgs)
' Make sure the right mouse button was clicked
If
e.Button <> MouseButtons.Right
Then
Return
End
If
' Hit test the drawing document
Dim
location
As
NPointF =
New
NPointF(e.Location)
Dim
shapes
As
NNodeList = view.Document.HitTest(location, -1, NFilters.Shape2D, view.ProvideDocumentHitTestContext())
If
shapes.Count = 0
Then
' No shape were found under the mouse cursor, so set the context
' menu of the view to null and return
view.ContextMenu =
Nothing
Return
End
If
' Create a context menu
Dim
contextMenu
As
ContextMenu =
New
ContextMenu(
New
MenuItem(){
New
MenuItem(
"Menu Item 1"
),
New
MenuItem(
"Menu Item 2"
),
New
MenuItem(
"-"
),
New
MenuItem(
"Menu Item 3"
) })
' Set the context menu of the drawing view
view.ContextMenu = contextMenu
End
Sub
Article ID: 17, Created On: 9/29/2010, Modified: 4/8/2013