0

我知道我可以向按钮、标签和文本框添加事件处理程序,如下所示:

AddHandler button1.click , AddressOf Subbutton1_click

实际上,我可以使用 Form Paint 事件中的图形绘制圆形、椭圆形、矩形或其他图形:

e.Graphics.DrawEllipse(pen1, 0.0F, 0.0F, 200.0F, 200.0F)

那行得通,但是我怎样才能为我刚刚绘制的图形添加一个事件处理程序?

任何帮助将不胜感激。

提前致谢

4

2 回答 2

2

您可以让一个事件引发另一个事件。让我们从使用 GraphicsPath 存储形状并绘制它的基本表单开始:

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

现在您要添加一个事件,以便其他一些类可以看到被单击的形状:

Public Event ShapeClick As EventHandler

您编写了一个引发事件的受保护虚拟方法,这是标准 .NET 事件引发模式的一部分:

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

并且您需要注意用户点击表单。您将检查形状是否被单击,如果是这种情况,则引发事件:

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
于 2013-04-17T22:33:56.923 回答
0

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.

于 2013-04-17T21:39:25.737 回答