将事件处理程序添加到绘制的图形中 [英] Add event handler to graphics figure painted

查看:74
本文介绍了将事件处理程序添加到绘制的图形中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know I can add event handlers to buttons, labels and textboxes like this:

AddHandler button1.click , AddressOf Subbutton1_click

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

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?

任何帮助将不胜感激.

预先感谢

推荐答案

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

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

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

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

这篇关于将事件处理程序添加到绘制的图形中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆