본문 바로가기

자료

[C#/vb.net] vb.net 에서 동적 컨트롤에 익명매소드를 이용해서 이벤트 걸기

728x90

익명매소드(이름이 없는 매소드)

1. 객체 생성과 동시에 구현할 때

2. 일회성으로 사용할때

사용 예:)

AddHandler CB.CheckedChanged, Sub(S, O) MsgBox(S.tag)

아래 프로시저를 실행 후

  Private Sub LoadTimer_Tick(sender As Object, e As EventArgs) Handles LoadTimer.Tick
        LoadTimer.Stop()
        Dim T As String
        Dim URL As String = "https://section.blog.naver.com/ajax/DirectoryList.nhn"
        With CreateObject("WinHttp.WinHttpRequest.5.1")
            .Open("GET", URL)
            .SetRequestHeader("Host", "section.blog.naver.com")
            .SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0")
            .SetRequestHeader("Accept", "application/json, text/plain, */*")
            .SetRequestHeader("Accept-Language", "ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3")
            .SetRequestHeader("Referer", "https://section.blog.naver.com/BlogHome.nhn?directoryNo=0&currentPage=1&groupId=0")
            .SetRequestHeader("Connection", "keep-alive")
            If Len(Cookie) Then .SetRequestHeader("Cookie", Cookie)
            .SetRequestHeader("TE", "Trailers")
            .Send()
            .WaitForResponse() : Application.DoEvents()
            'T = System.Text.Encoding.Default.GetString(.ResponseBody)
            T = .ResponseText
        End With
        T = T.Substring(T.IndexOf("{"))
        Dim J As Object = JsonConvert.DeserializeObject(T)
        For Each result As Object In J("result")
            Dim activeDirectoryName As String = result("name")
            Dim activeDirectorySeq As String = result("seq")
            Dim LB As New Label
            LB.Text = String.Format("[{0}]", activeDirectoryName)
            LB.AutoSize = True
            LB.Font = New Font("맑은 고딕", 11, FontStyle.Bold)
            FlowLayoutPanel1.Controls.Add(LB)
            For Each directoryList As Object In result("directoryList")
                Dim DirectoryName As String = directoryList("name")
                Dim DirectorySeq As String = directoryList("seq")
                Dim CB As New CheckBox
                CB.Text = DirectoryName
                CB.AutoSize = True
                CB.Checked = True
                CB.Tag = String.Format("https://section.blog.naver.com/ThemePost.nhn?directoryNo={0}&activeDirectorySeq={1}&currentPage={2}", DirectorySeq, activeDirectorySeq, "{0}")
                AddHandler CB.CheckedChanged, Sub(S, O) MsgBox(S.tag)
                FlowLayoutPanel1.Controls.Add(CB)
                If FlowLayoutPanel1.ClientRectangle.Height < CB.Top + CB.Height Then GroupBox7.Height = GroupBox7.Height + (CB.Top + CB.Height - FlowLayoutPanel1.ClientRectangle.Height)
            Next
        Next
    End Sub
728x90