How would you add a text box at runtime?
Printable View
How would you add a text box at runtime?
Create an Invisible Textbox Control Array at Design by adding a Textbox, setting it's Visible property to False and it's Index property to Zero.
Then at runtime, load instances of the Textbox and process the events through the Textbox Control Array Events identifying the different instances by the Index value passed to the event, i.e.Code:Option Explicit
Private Sub Command1_Click()
Load txtArray(txtArray.Count)
With txtArray(txtArray.Count - 1)
.Text = "Text" & txtArray.Count - 1
.Move .Width * (.Index - 1), 0
.Visible = True
End With
End Sub
Private Sub txtArray_KeyPress(Index As Integer, KeyAscii As Integer)
Caption = "Typing in Text" & Index & "..."
End Sub
If you want to create them from scratch use the following method (VB6 only)
If you have VB5, use CreateWindowEx APICode:Private Sub Command1_Click()
Controls.Add "VB.TextBox", "Text1"
Me!Text1.Move 0, 0
Me!Text1.Caption = "Text1"
Me!Text1.Visible = True
End Sub
Code:Private Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Const WS_CHILD = &H40000000
Private WithEvents btn As CommandButton
Private Sub Form_Load()
retval = CreateWindowEx(0&, "Edit", "Edit1", WS_CHILD, 32, 32, 64, 64, Me.hwnd, 0, App.hInstance, ByVal 0&)
ShowWindow retval, 1
End Sub