- 사용한 컨트롤 : DateTimepicker 1개, Button 1개, Label 4개
전체 소스 코드
Form1.vb
Imports System.Runtime.InteropServices
Imports System.Net
Imports System.IO
Imports System.Net.Json
Public Class Form1
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
'AP01 : 환율, AP02 : 대출금리, AP03 : 국제금리
Dim strURL As String = "https://www.koreaexim.go.kr/site/program/financial/interestJSON?authkey=" + _
"DhvTGvqzZYg58GZMbo0C2eBhOHnLtj10&searchdate=" + _
dtp.Value.ToString("yyyyMMdd") + "&data=" + _
"AP02"
Dim hwr As HttpWebRequest = WebRequest.Create(strURL)
hwr.ContentType = "application/json"
Using hwrResult As HttpWebResponse = CType(hwr.GetResponse(), HttpWebResponse)
Dim sr As Stream = hwrResult.GetResponseStream()
Using srd As StreamReader = New StreamReader(sr)
Dim strResult As String = srd.ReadToEnd()
Dim strErr As String = ""
If (Not StringToJson(strResult, strErr)) Then
MessageBox.Show(strErr, "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
End Using
sr.Close()
hwrResult.Close()
End Using
End Sub
Private Function StringToJson(ByVal strTmp As String, ByRef strErr As String) As Boolean
If strTmp.Length < 3 Then
strErr = "영업일이 아닙니다. 확인 후 이용해 주세요."
Return False
End If
Dim jtr As JsonTextParser = New JsonTextParser()
'string 문자열 -> json 으로 변환
Dim jo As JsonObject = jtr.Parse(strTmp)
Dim jac As JsonArrayCollection = CType(jo, JsonArrayCollection)
Dim iRow As Integer = 0
Dim joc As JsonObjectCollection
For Each joc In jac
iRow += 1
If (joc("result").ToString().Contains("1")) Then
lbl1.Text = joc("sfln_intrc_nm").ToString().Split(":")(1).Replace("""", " ").Trim()
lbl2.Text = joc("int_r").ToString().Split(":")(1).Replace("""", " ").Trim()
End If
Next
Return True
End Function
End Class
아래의 그림과 같이 Button Click Event 를 살펴 보면
strURL 부분의 지워진 부분은 각자 한국 수출입 은행에서 받은 인증키를 입력 하면 됩니다.
- 사용한 컨트롤 : DateTimepicker 1개, Button 1개, Listview 1개
전체 소스 코드
Form1.vb
Imports System.Net.Json
Imports System.IO
Imports System.Net
Public Class Form1
Public Declare Function CreateRoundRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long, ByVal X3 As Long, ByVal Y3 As Long) As Long
Public Declare Function SetWindowRgn Lib "user32" (ByVal hWnd As Long, ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
SetRoundControl(listView1, 15)
MyBase.OnLoad(e)
End Sub
Private Sub Form1_ResizeEnd(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.ResizeEnd
SetRoundControl(listView1, 15)
End Sub
Private Sub SetRoundControl(ByVal ct As Control, ByVal iValue As Integer)
Dim ip As IntPtr = CreateRoundRectRgn(0, 0, ct.Width, ct.Height, iValue, iValue)
Dim i As Integer = SetWindowRgn(ct.Handle, ip, True)
End Sub
Private Function StringToJson(ByVal strTmp As String, ByRef strErr As String) As Boolean
If strTmp.Length < 3 Then
strErr = "영업일이 아닙니다. 확인 후 이용해 주세요."
Return False
End If
listView1.Items.Clear()
Dim jtr As JsonTextParser = New JsonTextParser()
'string 문자열 -> json 으로 변환
Dim jo As JsonObject = jtr.Parse(strTmp)
Dim jac As JsonArrayCollection = CType(jo, JsonArrayCollection)
Dim iRow As Integer = 0
Dim joc As JsonObjectCollection
For Each joc In jac
iRow += 1
'Display
JsonDataSet(iRow, joc)
Next
Return True
End Function
Private Sub JsonDataSet(ByVal iRow As Integer, ByVal joc As JsonObjectCollection)
'success
If joc("result").ToString().Contains("1") Then
Dim lvi As ListViewItem = New ListViewItem()
lvi.Text = iRow.ToString()
'ex) cur_nm : "미국 달러" => split(:)[1] "미국 달러" => Replace " 공백 치환으로 미국 달러
lvi.SubItems.Add(joc("cur_unit").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("cur_nm").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("ttb").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("tts").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("deal_bas_r").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("bkpr").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("yy_efee_r").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("kftc_deal_bas_r").ToString().Split(":")(1).Replace("""", " ").Trim())
lvi.SubItems.Add(joc("kftc_bkpr").ToString().Split(":")(1).Replace("""", " ").Trim())
listView1.Items.Add(lvi)
End If
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
'AP01 : 환율, AP02 : 대출금리, AP03 : 국제금리
'ex) 2015-01-01, 20150101, (DEFAULT)현재일
'(요청) https://www.koreaexim.go.kr/site/program/financial/exchangeJSON?authkey=AUTHKEY1234567890&searchdate=20180102&data=AP01
'(응답) [{"result":1,"cur_unit":"AED","ttb":"288.78","tts":"294.61","deal_bas_r":"291.7","bkpr":"291"
' ,"yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"291","kftc_deal_bas_r":"291.7"
' ,"cur_nm":"아랍에미리트 디르함"},"result":1,"cur_unit":"ATS","ttb":"0","tts":"0"
' ,"deal_bas_r":"93.52","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0"
' ,"kftc_deal_bas_r":"93.52","cur_nm":"오스트리아 실링"},{"result":1,"cur_unit":"AUD","ttb":"827.91","tts":"844.64","deal_bas_r":"836.28","bkpr":"836","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"836","kftc_deal_bas_r":"836.28","cur_nm":"호주 달러"},{"result":1,"cur_unit":"BEF","ttb":"0","tts":"0","deal_bas_r":"31.9","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"31.9","cur_nm":"벨기에 프랑"},{"result":1,"cur_unit":"BHD","ttb":"2,811.48","tts":"2,868.27","deal_bas_r":"2,839.88","bkpr":"2,839","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"2,839","kftc_deal_bas_r":"2,839.88","cur_nm":"바레인 디나르"},{"result":1,"cur_unit":"CAD","ttb":"844.72","tts":"861.79","deal_bas_r":"853.26","bkpr":"853","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"853","kftc_deal_bas_r":"853.26","cur_nm":"캐나다 달러"},{"result":1,"cur_unit":"CHF","ttb":"1,088.44","tts":"1,110.43","deal_bas_r":"1,099.44","bkpr":"1,099","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"1,099","kftc_deal_bas_r":"1,099.44","cur_nm":"스위스 프랑"},{"result":1,"cur_unit":"CNH","ttb":"162.01","tts":"165.28","deal_bas_r":"163.65","bkpr":"163","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"163","kftc_deal_bas_r":"163.65","cur_nm":"위안화"},{"result":1,"cur_unit":"DEM","ttb":"0","tts":"0","deal_bas_r":"657.98","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"657.98","cur_nm":"독일 마르크"},{"result":1,"cur_unit":"DKK","ttb":"171.14","tts":"174.59","deal_bas_r":"172.87","bkpr":"172","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"172","kftc_deal_bas_r":"172.87","cur_nm":"덴마아크 크로네"},{"result":1,"cur_unit":"ESP(100)","ttb":"0","tts":"0","deal_bas_r":"773","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"773","cur_nm":"스페인 페세타"},{"result":1,"cur_unit":"EUR","ttb":"1,274.04","tts":"1,299.77","deal_bas_r":"1,286.91","bkpr":"1,286","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"1,286","kftc_deal_bas_r":"1,286.91","cur_nm":"유로"},{"result":1,"cur_unit":"FIM","ttb":"0","tts":"0","deal_bas_r":"216.44","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"216.44","cur_nm":"핀란드 마르카"},{"result":1,"cur_unit":"FRF","ttb":"0","tts":"0","deal_bas_r":"196.18","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"196.18","cur_nm":"프랑스 프랑"},{"result":1,"cur_unit":"GBP","ttb":"1,432.82","tts":"1,461.77","deal_bas_r":"1,447.3","bkpr":"1,447","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"1,447","kftc_deal_bas_r":"1,447.3","cur_nm":"영국 파운드"},{"result":1,"cur_unit":"HKD","ttb":"135.75","tts":"138.5","deal_bas_r":"137.13","bkpr":"137","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"137","kftc_deal_bas_r":"137.13","cur_nm":"홍콩 달러"},{"result":1,"cur_unit":"IDR(100)","ttb":"7.82","tts":"7.97","deal_bas_r":"7.9","bkpr":"7","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"7","kftc_deal_bas_r":"7.9","cur_nm":"인도네시아 루피아"},{"result":1,"cur_unit":"ITL(100)","ttb":"0","tts":"0","deal_bas_r":"66.46","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"66.46","cur_nm":"이태리 리라"},{"result":1,"cur_unit":"JPY(100)","ttb":"941.53","tts":"960.56","deal_bas_r":"951.05","bkpr":"951","yy_efee_r":"0.96833","ten_dd_efee_r":"0.0242","kftc_bkpr":"951","kftc_deal_bas_r":"951.05","cur_nm":"일본 옌"},{"result":1,"cur_unit":"KRW","ttb":"0","tts":"0","deal_bas_r":"1","bkpr":"1","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"1","kftc_deal_bas_r":"1","cur_nm":"한국 원"},{"result":1,"cur_unit":"KWD","ttb":"3,509.87","tts":"3,580.78","deal_bas_r":"3,545.33","bkpr":"3,545","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"3,545","kftc_deal_bas_r":"3,545.33","cur_nm":"쿠웨이트 디나르"},{"result":1,"cur_unit":"MYR","ttb":"262.09","tts":"267.38","deal_bas_r":"264.74","bkpr":"264","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"264","kftc_deal_bas_r":"264.74","cur_nm":"말레이지아 링기트"},{"result":1,"cur_unit":"NLG","ttb":"0","tts":"0","deal_bas_r":"583.97","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"583.97","cur_nm":"네델란드 길더"},{"result":1,"cur_unit":"NOK","ttb":"129.44","tts":"132.05","deal_bas_r":"130.75","bkpr":"130","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"130","kftc_deal_bas_r":"130.75","cur_nm":"노르웨이 크로네"},{"result":1,"cur_unit":"NZD","ttb":"752.76","tts":"767.97","deal_bas_r":"760.37","bkpr":"760","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"760","kftc_deal_bas_r":"760.37","cur_nm":"뉴질랜드 달러"},{"result":1,"cur_unit":"SAR","ttb":"282.84","tts":"288.55","deal_bas_r":"285.7","bkpr":"285","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"285","kftc_deal_bas_r":"285.7","cur_nm":"사우디 리얄"},{"result":1,"cur_unit":"SEK","ttb":"129.3","tts":"131.91","deal_bas_r":"130.61","bkpr":"130","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"130","kftc_deal_bas_r":"130.61","cur_nm":"스웨덴 크로나"},{"result":1,"cur_unit":"SGD","ttb":"793.06","tts":"809.09","deal_bas_r":"801.08","bkpr":"801","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"801","kftc_deal_bas_r":"801.08","cur_nm":"싱가포르 달러"},{"result":1,"cur_unit":"THB","ttb":"32.57","tts":"33.22","deal_bas_r":"32.9","bkpr":"32","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"32","kftc_deal_bas_r":"32.9","cur_nm":"태국 바트"},{"result":1,"cur_unit":"USD","ttb":"1,056.23","tts":"1,077.56","deal_bas_r":"1,066.9","bkpr":"1,066","yy_efee_r":"2.69465","ten_dd_efee_r":"0.07485","kftc_bkpr":"1,071","kftc_deal_bas_r":"1,071.4","cur_nm":"미국 달러"},{"result":1,"cur_unit":"XOF","ttb":"0","tts":"0","deal_bas_r":"1.9618","bkpr":"0","yy_efee_r":"0","ten_dd_efee_r":"0","kftc_bkpr":"0","kftc_deal_bas_r":"1.9618","cur_nm":"씨에프에이 프랑(비씨에이오)"}]
Dim strURL As String = "https://www.koreaexim.go.kr/site/program/financial/exchangeJSON?authkey=" + _
"DhvTGvqzZYg58GZMbo0C2eBhOHnLtj10&searchdate=" + _
dtp.Value.ToString("yyyyMMdd") + "&data=" + _
"AP01"
Dim hwr As HttpWebRequest = WebRequest.Create(strURL)
hwr.ContentType = "application/json"
Using hwrResult As HttpWebResponse = CType(hwr.GetResponse(), HttpWebResponse)
Dim sr As Stream = hwrResult.GetResponseStream()
Using srd As StreamReader = New StreamReader(sr)
Dim strResult As String = srd.ReadToEnd()
Dim strErr As String = ""
If (Not StringToJson(strResult, strErr)) Then
MessageBox.Show(strErr, "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
End Using
sr.Close()
hwrResult.Close()
End Using
End Sub
End Class
아래의 그림과 같이 Button Click Event 를 살펴 보면
strURL 부분의 지워진 부분은 각자 한국 수출입 은행에서 받은 인증키를 입력 하면 됩니다.
Imports System.Runtime.InteropServices
Imports System.Net
Imports System.IO
Imports System.Xml
Public Class Form1
Public Declare Function CreateRoundRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long, ByVal X3 As Long, ByVal Y3 As Long) As Long
Public Declare Function SetWindowRgn Lib "user32" (ByVal hWnd As Long, ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long
Protected Overrides Sub OnLoad(e As EventArgs)
'Round Control
SetRoundControl(panel4, 15)
SetRoundControl(panel5, 15)
SetRoundControl(pnl1, 15)
SetRoundControl(pnl2, 15)
SetRoundControl(pnl3, 15)
SetRoundControl(pnl4, 15)
SetRoundControl(pnl5, 15)
Try
Dim dtNow As DateTime = Date.Now
If (dtNow.DayOfWeek = DayOfWeek.Sunday) Then
MessageBox.Show("오늘은 집계를 하지 않는 주말 입니다.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
'application.run() 이후에 종료 하는 것이므로... program.cs 에서 run 이전이면 application.exit()
Environment.Exit(1)
End If
SetCorona(dtNow)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
MyBase.OnLoad(e)
End Sub
Private Sub SetRoundControl(ct As Control, iValue As Integer)
Dim ip As IntPtr = CreateRoundRectRgn(0, 0, ct.Width, ct.Height, iValue, iValue)
Dim i As Integer = SetWindowRgn(ct.Handle, ip, True)
End Sub
Private Sub SetCorona(ByVal dt As DateTime)
Dim strURL As String = "http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson"
strURL += "?ServiceKey=" + "sb51casSGzjE5uqMHruw3gnN58sltRChTonZaqNIAqKvofyOsiupJE0Lwrlpyac%2BgZCD3QOWivSkk7CBZ5wOFQ%3D%3D" ' Service Key
strURL += "&pageNo=1"
strURL += "&numOfRows=10"
strURL += "&startCreateDt=" + dt.AddDays(-1).ToString("yyyyMMdd") '하루 전
strURL += "&endCreateDt=" + dt.ToString("yyyyMMdd") '오늘
Dim hwr As HttpWebRequest = CType(WebRequest.Create(strURL), HttpWebRequest)
hwr.Method = "GET"
Using hwrResult As HttpWebResponse = CType(hwr.GetResponse(), HttpWebResponse)
Dim sr As Stream = hwrResult.GetResponseStream()
'XML 파싱
XMLToRead(sr)
sr.Close()
hwrResult.Close()
End Using
End Sub
Private Sub XMLToRead(sr As Stream)
'=========================nodeList Comment===================================
'기준일 STATEDT
'기준시간 STATETIME
'확진자수 DECIDECNT
'격리해제수 CLEARCNT
'검사진행수 EXAMCNT
'사망자수 DEATHCNT
'치료중 환자수 CARECNT
'결과음성 수 RESUTLNEGCNT
'누적검사수 ACCEXAMCNT
'누적검사완료수 ACCEXAMCOMPCNT
'누적확진률 ACCDEFRATE
'등록일시 CREATEDT
'수정일시 UPDATEDT
Dim xd As XmlDocument = New XmlDocument()
'XML 문서로...
xd.Load(sr)
Dim xnl As XmlNodeList = xd.GetElementsByTagName("item") '접근할 노드 (대소문자 구분 해야 됨.)
Dim idecideCnt As Integer = 0
Dim iExamCnt As Integer = 0
Dim iclearCnt As Integer = 0
Dim dbAccDefRate As Double = 0.0
Dim ideathCnt As Integer = 0
Dim icareCnt As Integer = 0
'전날 누적 확진자 수
Dim iBeforeDec As Integer = 0
Dim xn As XmlNode
For Each xn In xnl
If xn("stateDt").InnerText = DateTime.Now.ToString("yyyyMMdd") Then
'기준 일시
lblDate.Text = xn("stateDt").InnerText + " " + xn("stateTime").InnerText
'확진자 수
idecideCnt = Convert.ToInt32(xn("decideCnt").InnerText)
'검사 진행
iExamCnt = Convert.ToInt32(xn("examCnt").InnerText)
'격리 해제
iclearCnt = Convert.ToInt32(xn("clearCnt").InnerText)
'누적 확진률
dbAccDefRate = Convert.ToDouble(xn("accDefRate").InnerText)
'사망자
ideathCnt = Convert.ToInt32(xn("deathCnt").InnerText)
'치료중인환자
icareCnt = Convert.ToInt32(xn("careCnt").InnerText)
Else
'어제 까지 누적 확진자 수
iBeforeDec = Convert.ToInt32(xn("decideCnt").InnerText)
End If
Next 'foreach
'오늘까지 누적 확진자 수 - 어제까지 누적 확진자 수
lblDec.Text = String.Format("{0:#,###,000}", idecideCnt - iBeforeDec)
lbl1.Text = String.Format("{0:#,###,000}", iExamCnt)
lbl2.Text = String.Format("{0:#,###,000}", iclearCnt)
lblAccDefRate.Text = String.Format("{0:0.00}", dbAccDefRate) + " %"
lbl3.Text = String.Format("{0:#,###,000}", ideathCnt)
lbl4.Text = String.Format("{0:#,###,000}", icareCnt)
lbl5.Text = String.Format("{0:#,###,000}", idecideCnt)
End Sub
End Class
*VBNET String 을 Byte 로 Byte 를 String 으로 String <-> Char 변환 예제...
- 사용한 컨트롤: Button 3개, TextBox 1개
전체 소스 코드
Form1.vb
Public Class Form1
Dim a As String = "ㄱㄴㄷ123abc"
Dim bb As Byte() = Nothing
Dim bc As Byte() = Nothing
Dim bd As Byte() = Nothing
Dim be As Byte() = Nothing
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
'String => Byte
bb = System.Text.Encoding.Default.GetBytes(a)
bc = System.Text.Encoding.Unicode.GetBytes(a)
bd = System.Text.Encoding.UTF8.GetBytes(a)
be = System.Text.Encoding.ASCII.GetBytes(a)
textBox1.Text = "String -> Byte 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "길이 " + System.Environment.NewLine
textBox1.Text += "Default: " + bb.Length.ToString() + System.Environment.NewLine
textBox1.Text += "Unicode: " + bc.Length.ToString() + System.Environment.NewLine
textBox1.Text += "UTF8: " + bd.Length.ToString() + System.Environment.NewLine
textBox1.Text += "ASCII: " + be.Length.ToString() + System.Environment.NewLine
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
'Byte => String
'바이트 배열에 아무것도 없으면...
If (bb Is Nothing) And (bc Is Nothing) And (bd Is Nothing) And (be Is Nothing) Then
MessageBox.Show("String -> Byte 변환 버튼 클릭 후 이용해 주세요.", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Return
End If
textBox1.Text += "Byte -> String 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "Default: " + System.Text.Encoding.Default.GetString(bb) + System.Environment.NewLine
textBox1.Text += "Unicode: " + System.Text.Encoding.Unicode.GetString(bc) + System.Environment.NewLine
textBox1.Text += "UTF8: " + System.Text.Encoding.UTF8.GetString(bd) + System.Environment.NewLine
textBox1.Text += "ASCII: " + System.Text.Encoding.ASCII.GetString(be) + System.Environment.NewLine '<- 한글 깨짐 한글 유니코드 변환X
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
Private Sub button3_Click(sender As Object, e As EventArgs) Handles button3.Click
'String <=> Char
Dim sTmp As String = "가나다123abc"
Dim cTmp As Char() = sTmp.ToCharArray()
textBox1.Text += "String -> Char 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "Char 길이: -> " + cTmp.Length.ToString() + System.Environment.NewLine
textBox1.Text += "Char -> String 로 변환 ============== " + System.Environment.NewLine
textBox1.Text += "변환: " + New String(cTmp) + System.Environment.NewLine
textBox1.Text += "===================================== " + System.Environment.NewLine + System.Environment.NewLine
End Sub
End Class
* VBNET Listview Column Auto Size (컬럼 사이즈 자동) 예제...
-사용한 컨트롤: Listview 1개
전체 소스 코드
Form1.vb
Public Class Form1
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
'예제 데이터 삽입...
For i As Integer = 0 To 9
Dim lvi As ListViewItem = New ListViewItem()
lvi.Text = (i + 1).ToString()
lvi.SubItems.Add("TEST " + (i + 1).ToString())
listView1.Items.Add(lvi)
Next
''리스트 뷰 컬럼 Auto Size
''리스트 뷰 컬럼 얻어오기...
'listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
'Dim cc As ListView.ColumnHeaderCollection = listView1.Columns
'For j As Integer = 0 To cc.Count - 1
' Dim iColWidth As Integer = TextRenderer.MeasureText(cc(j).Text, listView1.Font).Width + 10
' '대입
' If iColWidth > cc(j).Width Then
' cc(j).Width = iColWidth
' End If
'Next
End Sub
End Class
Imports System.Net.Json
Imports System.Net
Imports System.IO
Public Class Form1
Dim iCount As Integer = 0
Dim ltResult As List(Of Integer) = New List(Of Integer)()
Private Function IsNullString(ByVal str As String) As Boolean
Return String.IsNullOrEmpty(str)
End Function
Private Function IsInt(ByVal ob As Object) As Integer
If ob Is Nothing Then
Return 0
End If
Dim iCheck As Integer = 0
Dim bCheck As Boolean = Integer.TryParse(ob.ToString(), iCheck)
If Not bCheck Then
Return 0
End If
Return iCheck
End Function
Private Function IsCheck() As Boolean
'문자열 체크.
If IsNullString(TextBox1.Text) And _
IsNullString(TextBox2.Text) And _
IsNullString(TextBox3.Text) And _
IsNullString(TextBox4.Text) And _
IsNullString(TextBox5.Text) And _
IsNullString(TextBox6.Text) Then
MessageBox.Show("빈 값일 순 없습니다.")
Return False
End If
'숫자 체크...
If IsInt(TextBox1.Text) And _
IsInt(TextBox2.Text) And _
IsInt(TextBox3.Text) And _
IsInt(TextBox4.Text) And _
IsInt(TextBox5.Text) And _
IsInt(TextBox6.Text) Then
MessageBox.Show("숫자만 입력 해 주세요.")
Return False
End If
'회차 번호 체크...
If IsInt(TextBox8.Text) = 0 And IsNullString(TextBox8.Text) Then
MessageBox.Show("숫자만 입력 또는 빈 값일 순 없습니다.")
TextBox8.Text = ""
TextBox8.Focus()
Return False
End If
Return True
End Function
Private Function GetHttpLottoString(ByVal strUri As String) As String
Dim strResponseText As String = String.Empty
Dim request As HttpWebRequest = CType(WebRequest.Create(strUri), HttpWebRequest)
request.Method = "GET"
'웹리퀘스트 타임아웃
request.Timeout = 20 * 1000 ' 20초
'request.Headers.Add("Authorization", "BASIC SGVsbG8="); // 헤더 추가 방법
'응답 받기
Using hwr As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
'응답이 정상적으로 이루어 졌으면...
If hwr.StatusCode = HttpStatusCode.OK Then
Dim respStream As Stream = hwr.GetResponseStream()
Using sr As StreamReader = New StreamReader(respStream)
strResponseText = sr.ReadToEnd()
End Using
Else
strResponseText = ""
End If
End Using
Return strResponseText
End Function
Private Sub Check_Result(ByVal iNumber As Integer)
'-2 한 값은 마집막 보너스 넘버는 체크 안함...
For i As Integer = 0 To ltResult.Count - 2
If iNumber = ltResult(i) Then
iCount = iCount + 1
Return
End If
Next
End Sub
Private Sub MessageResult(ByVal iBonus As Integer)
Select Case iCount
Case 6
lblResult.Text = "축하 드립니다. 1등에 당첨 되셨습니다."
Case 5
If iBonus = 1 Then
lblResult.Text = "축하 드립니다. 2등에 당첨 되셨습니다."
Else
lblResult.Text = "축하 드립니다. 3등에 당첨 되셨습니다."
End If
Case 4
lblResult.Text = "축하 드립니다. 4등에 당첨 되셨습니다."
Case 3
lblResult.Text = "축하 드립니다. 5등에 당첨 되셨습니다."
Case Else
lblResult.Text = "꽝 입니다. 다음 기회에...반드시 성공을..."
End Select
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ltLottoNumber As List(Of Integer) = New List(Of Integer)
Dim iBonus As Integer = 0
'초기화...
ltResult.Clear()
iCount = 0
'텍스트 박스들 체크...
If Not IsCheck() Then
Return
End If
ltLottoNumber.Add(Convert.ToInt32(TextBox1.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox2.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox3.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox4.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox5.Text.Trim()))
ltLottoNumber.Add(Convert.ToInt32(TextBox6.Text.Trim()))
'로또 회차 넘버 불러오기...
Dim strReturnValue As String = GetHttpLottoString("https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=" + TextBox8.Text)
If strReturnValue = "" Then
MessageBox.Show("Lotto Number 불러오기 실패...")
Return
End If
'json 파싱
Dim jtr As Json.JsonTextParser = New Json.JsonTextParser()
Dim jo As Json.JsonObject = jtr.Parse(strReturnValue)
Dim jac As Json.JsonObjectCollection = jo
'불러오기가 성공 하면...
If jac("returnValue").GetValue().ToString() = "success" Then
ltResult.Add(Convert.ToInt32(jac("drwtNo1").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo2").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo3").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo4").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo5").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("drwtNo6").GetValue().ToString().Trim()))
ltResult.Add(Convert.ToInt32(jac("bnusNo").GetValue().ToString().Trim()))
TextBox7.Text = jac("bnusNo").GetValue().ToString().Trim()
End If
'Check Result
For i As Integer = 0 To ltLottoNumber.Count - 1
Check_Result(ltLottoNumber(i))
If ltLottoNumber(i) = ltResult(ltResult.Count - 1) Then
iBonus = 1
End If
MessageResult(iBonus)
Next
End Sub
Private Sub TextBox8_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox8.KeyDown
If e.KeyCode = Keys.Enter Then
Button1_Click(Nothing, Nothing)
End If
End Sub
End Class
* VBNET 랜덤(Random) 클래스를 이용한 간단한 로또(Lotto) 숫자 생성 예제...
- 사용한 컨트롤 : Button 1개, Label 1개, TextBox 1개
전체 소스 코드
Form1.vb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = Create_LottoNumber()
End Sub
Private Function Create_LottoNumber() As String
Dim strTmp As String = ""
Dim strNumber As String = ""
Dim strBonusNumber As String = ""
Dim imsiNum(7) As Integer
For i As Integer = 0 To 6
Dim rnd As Random = New Random()
Dim bCheck As Boolean = False
imsiNum(i) = rnd.Next(1, 45)
For j As Integer = 0 To i - 1
'같은 번호 이면... 다시
If imsiNum(i) = imsiNum(j) Then
i = i - 1
bCheck = True
End If
Next
'문자열로 합치기
If Not bCheck Then strTmp += imsiNum(i).ToString() + ", "
Next
'Lotto Number 만 가려내기
strNumber = strTmp.Substring(0, strTmp.LastIndexOf(",") - 3)
'마지막 , 제거
strNumber = strNumber.Substring(0, strNumber.LastIndexOf(","))
'보너스 번호 가져 오기
strBonusNumber = strTmp.Substring(strTmp.LastIndexOf(",") - 5, 2).Trim()
strBonusNumber = strBonusNumber.Substring(0, strBonusNumber.LastIndexOf(","))
Return "LottoNumber : " + strNumber + " BonusNumber : " + strBonusNumber
End Function
End Class
Public Class Form1
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Dim ofd As OpenFileDialog = New OpenFileDialog()
ofd.Filter = "JPG Files(*.jpg) | *.jpg"
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
pictureBox1.Image = New Bitmap(ofd.FileName)
End If
End Sub
Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
'20 씩 밝기 증가
pictureBox1.Image = BrightnessImage(pictureBox1.Image, 20)
End Sub
Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click
'20 씩 밝기 감소
pictureBox1.Image = BrightnessImage(pictureBox1.Image, -20)
End Sub
Private Function BrightnessImage(ByVal imSource As Image, ByVal iBrightness As Integer) As Bitmap
Dim btTmp As Bitmap = New Bitmap(imSource)
Dim cTmp As Color
Dim iR As Integer, iG As Integer, iB As Integer
For iY As Integer = 0 To btTmp.Height - 1
For iX As Integer = 0 To btTmp.Width - 1
cTmp = btTmp.GetPixel(iX, iY)
iR = Math.Max(0, Math.Min(255, cTmp.R + iBrightness))
iG = Math.Max(0, Math.Min(255, cTmp.G + iBrightness))
iB = Math.Max(0, Math.Min(255, cTmp.B + iBrightness))
cTmp = Color.FromArgb(iR, iG, iB)
btTmp.SetPixel(iX, iY, cTmp)
Next
Next
Return btTmp
End Function
End Class