我将有一个包含60个线形的表单(使用Visual Studios PowerPack)。我希望用户能够使用键盘上的左右按钮旋转90度的形状。
最好的方法是什么?我尝试过其他方法,但这相当于1000行代码,我还在学习,我想知道最佳实践。
非常感谢!
答案 0 :(得分:1)
我暂时假设您已经编写了一次处理几何图形的部件,并询问如何重复使用代码,而不是将其复制为60行。这很重要,因为它不是100%清楚你是否围绕中点或起点周围旋转,因为LineShape类型确实区分了起点和终点。没有这些信息,我无法为您编写几何代码。
第一部分并不是那么糟糕。我们只设置了几种可以处理旋转任何行的方法:
'Note that rotating a line 90 degrees around it's midpoint
' will give the same result whether you go clockwise or counterclockwise,
' but I figure you'll want to adapt this for other shapes later, or that
' you're rotating around the line's starting point
Private Sub RotateClockwise(ByVal line As LineShape)
'Code to rotate the passed line clockwise here
Dim x1 As Integer = line.X1
Dim y1 As Integer = line.Y1
Dim x2 As Integer = line.X2
Dim y2 As Integer = line.Y2
End Sub
Private Sub RotateCounterclockwise(ByVal line As LineShape)
'Code to rotate the passed line counter-clockwise here
End Sub
Private Sub LineShape_KeyDown(Byval sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
'Which line?
Dim line As LineShape = TryCast(sender, LineShape)
If line Is Nothing Then Exit Sub
'Left key?
If e.KeyCode = Keys.Left Then RotateCounterclockwise(line)
'Right key?
If e.KeyCode = Keys.Right Then RotateClockwise(line)
End Sub
这是棘手的地方。请注意,上面的事件处理程序缺少Handles
关键字。我们希望将LineShape控件的所有的KeyDown
事件处理程序连接到这个方法。这将有点重复,因为它意味着表单上每行的一行额外代码,但它比需要为所有行编写上述代码更好:< / p>
Dim Lines As New List(Of LineShape)()
Lines.Add(LineShape1)
Lines.Add(LineShape2)
'...
Lines.Add(LineShape60)
For Each Line As LineShape In Lines
AddHandler Line.KeyDown, AddressOf LineShape_KeyDown
Next
在<{em> InitializeComponent()
方法之后,该代码会出现在您的表单构造函数中。
如果LineShape类型是真正的控件(For EAch Line In Me.Controls.OfType(Of LineShape)()
),我可以做得更好,但文档显示这实际上是Component
,而不是Control
。
答案 1 :(得分:0)
或者,您可以将LineShape
子类化并将“rotatability”构建到新类中:
Imports Microsoft.VisualBasic.PowerPacks
Public Class MySmartLine
Inherits LineShape
Private Sub RotateClockwise()
'Code to rotate clockwise here
Me.X1 = ...
Me.X2 = ...
End Sub
Private Sub RotateAntiClockwise()
'Code to rotate anti clockwise here
End Sub
Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
MyBase.OnKeyDown(e)
If e.KeyCode = Keys.Left Then
RotateAntiClockwise()
End If
If e.KeyCode = Keys.Right Then
RotateClockwise()
End If
End Sub
End Class
构建项目后,自定义MySmartLine
组件将显示在您的工具箱中,您可以使用它来代替LineShape
。