티스토리 뷰

728x90

윈도우 폼(Forms) 응용 프로그램에서 개별 폼에 포함되어 있는 컨트롤은 비주얼스튜디오 디자이너 화면에서 도구 박스에서 끌어다놓기 방식으로 추가 및 설정하는 것이 일반적인 방법이지만 프로그램 실행 과정에서 특정 조건이나 옵션에 따라서 컨트롤을 추가하거나 삭제할 수 있습니다. 실행중 컨트롤 추가 및 삭제는 "폼이름.Designer.vb"의 형태로 저장하는 디자이너 코드 파일의 흐름을 따라하기 하면 됩니다.

Partial Class Form1
    Inherits System.Windows.Forms.Form

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    Private components As System.ComponentModel.IContainer

    '참고: 다음 프로시저는 Windows Form 디자이너에 필요합니다.
    '수정하려면 Windows Form 디자이너를 사용하십시오.  
    '코드 편집기를 사용하여 수정하지 마십시오.
    Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(98, 128)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "OK"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 12.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(284, 262)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub
    Friend WithEvents Button1 As System.Windows.Forms.Button

End Class

동적으로 컨트롤을 추가하는 과정은 아래의 그림과 같이 컨트롤 오브젝트 추가, 컨트롤에 대한 옵션 설정, 폼 Controls에 오브젝트 등록의 순서로 진행합니다.



Public Class Form1
    WithEvents Button2 As System.Windows.Forms.Button
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click, Button2.Click
        If sender.Equals(Button1) And Button2 Is Nothing Then
            Button2 = New System.Windows.Forms.Button()
            Button2.Location = New System.Drawing.Point(10, 10)
            Button2.Name = "Button2"
            Button2.Size = New System.Drawing.Size(75, 23)
            Button2.TabIndex = 0
            Button2.Text = "Button2"
            Button2.UseVisualStyleBackColor = True
            Controls.Add(Button2)
        ElseIf sender.Equals(Button1) And Button2 IsNot Nothing Then
            If Button2.Visible Then Button2.Visible = False Else Button2.Visible = True
        ElseIf sender.Equals(Button2) Then
            If Button1.Visible Then Button1.Visible = False Else Button1.Visible = True
        End If
    End Sub
End Class

위의 코드 예제는 버튼 하나를 가진 폼이 기동되어 버튼을 누르면 동적으로 새로운 버튼을 추가합니다. 기존 버튼과 동적으로 추가한 버튼은 하나의 이벤트 처리 루틴을 사용하도록 클릭 이벤트 처리 루틴의 선언부에 "Handles Button1.Click, Button2.Click"와 같이 대상 컨트롤을 콤마(,)로 구분해서 기입해 주었습니다. 새로운 컨트롤이 추가된 다음에는 한쪽의 버튼을 클릭하면 다른 버튼이 보이기/숨기기를 버튼의 상태에 따라 수행합니다.

컨트롤 오브젝트를 "New System.Windows.Forms.Button()"와 같이 추가하기 전에 해당 오브젝트를 선언할 위치는 폼 클래스(위의 예제에서는 Form1)의 범위로 선언해야 폼의 유효성과 컨트롤을 일치시킬 수 있습니다. 또한 해당 컨트롤에 대해서 이벤트 처리가 필요한 경우에는 오브젝트 선언 앞에 "WithEvents"를 붙여주어야 합니다.

컨트롤에 대한 크기와 위치 같은 옵션을 설정한 다음에는 마지막으로 폼의 Controls 컬렉션에 추가하여 옵션을 설정한 오브젝트를 "Controls.Add(Button2)"와 같이 등록하면 됩니다. "Controls.Add(Button2)"와 같은 등록 문장은 폼 뿐만아니라 그룹박스와 레이아웃 판넬과 같은 컨트롤에 대해서도 적용하는 것으로 추가한 컨트롤이 어디에 속하는 지를 지정하는 과정으로 이해할 수 있습니다. 레이아웃 판넬에 컨트롤을 추가하게 되면 폼>레이아웃 판넬>컨트롤로 이어지는 구조적인 관계를 가집니다. 아래의 그림은 두번째 버튼을 생성한 화면 입니다.



컨트롤 삭제는 우선 "Controls.Remove(Button2)" 처럼 Controls 컬렉션에서 해당 컨트롤을 등록 해제하고 컨트롤 자체를 Dispose()등으로 제거하면 됩니다.

728x90
댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함