VB动态控件加载

2024-12-02 11:24:29
推荐回答(3个)
回答1:

下面举例说明,请参考

在窗体上加入控件text1,label1(在属性窗口内设置index=0),然后复制下面代码,运行即可:

Option Explicit
Dim Mx As Integer, My As Integer

Private Sub Form_DblClick()
With Text1
.Text = ""
.Left = Mx
.Top = My
.Visible = True
End With
End Sub

Private Sub Form_Load()
Text1.Visible = False
Label1(0).Visible = False
Label1(0).AutoSize = True
End Sub

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Mx = X
My = Y
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
Dim i As Integer
i = Label1.UBound + 1
Load Label1(i)
With Label1(i)
.Top = Text1.Top
.Left = Text1.Left
.Caption = Text1.Text
.Visible = True
End With
Text1.Visible = False
End If
End Sub

回答2:

Dim X0, Y0 As Long
Dim l1 As Control
Dim WithEvents t1 As TextBox '是创建出来的控件能响应事件
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long '获得鼠标位置的API函数。
Private Type POINTAPI
X As Long
Y As Long
End Type

Private Sub Form_DblClick()
Dim P As POINTAPI
GetCursorPos P
X0 = P.X: Y0 = P.Y
Set t1 = Controls.Add("VB.Textbox", "Text1")

With t1:
.Left = 1000
.Top = 400
.FontSize = 24
.Visible = True
.Text = ""
End With

End Sub
Private Sub t1_KeyPress(KeyAscii As Integer)
If KeyAscii = 13 Then
Set l1 = Controls.Add("VB.Label", "Label1")
With l1
.Visible = True
.Caption = t1.Text
.Left = X0
.Top = Y0
.AutoSize = True
.FontSize = 24
End With
End If

End Sub

回答3:

代码:
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Type POINTAPI

x As Long

y As Long

End Type

prive from_dbclick()
dim ShowLabel as vb.label

Dim pt As POINTAPI
dim x as long

dim y as long
x=pt.x
y=pt.y
dim labelX as label
labelx=load(showlabel)
labelx.top=y
labelx.left=x
labelx.caption="动态加载的LABEL"
labelx=new showlabel
end sub