Reputation: 708
I know I can add event handlers to buttons, labels and textboxes like this:
AddHandler button1.click , AddressOf Subbutton1_click
I can actually draw a circle, ellipse, rectangle or another figure using graphics inside the Form Paint event:
e.Graphics.DrawEllipse(pen1, 0.0F, 0.0F, 200.0F, 200.0F)
That works, but how can I add an event handler for that graphics that I've just drawn?
Any help will be appreciated.
Thanks in advance
Upvotes: 0
Views: 2648
Reputation: 942257
You can have one event raise another event. Lets start with a basic form that uses a GraphicsPath to store the shape and paints it:
Imports System.Drawing.Drawing2D
Public Class Form1
Private Shape As GraphicsPath
Public Sub New()
InitializeComponent()
Shape = New GraphicsPath()
Shape.AddEllipse(0, 0, 200.0F, 200.0F)
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
e.Graphics.DrawPath(Pens.Black, Shape)
MyBase.OnPaint(e)
End Sub
End Class
Now you want to add an event so that some other class can see the shape being clicked:
Public Event ShapeClick As EventHandler
You write a protected virtual method that raises the event, part of the standard .NET event raising pattern:
Protected Overridable Sub OnShapeClick(ByVal e As EventArgs)
'--- Note: you can write code here to respond to the click
RaiseEvent ShapeClick(Me, e)
End Sub
And you need to pay attention to the user clicking on the form. You'll check if the shape was clicked and raise the event if that was the case:
Protected Overrides Sub OnMouseUp(ByVal e As System.Windows.Forms.MouseEventArgs)
If Shape.IsVisible(e.Location) Then OnShapeClick(EventArgs.Empty)
MyBase.OnMouseUp(e)
End Sub
Upvotes: 2
Reputation: 126
You could intercept the windows or views (etc..., i don't know what you are using) click event, so every time you click somewhere that function will be called.
And in that click event check if it is inside your custom drawn element. You will need to save the elements properties first though and it would use a lot of resources to iterate through all the elements.
I don't know if this is acceptable in your case or not and what you are actually trying to accomplish.
Upvotes: 0