使用 Google 的 Web API 创建二维码(2)

当用户按下“制作”按钮时,我们将会读到一段TextBox文本,并将其传送到QrBox Data Property中,并且触发刷新方法。为了开始针对谷歌Charts的远程查询,按按钮产生的代码将会简单如下:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    QrBox1.Data = TextBox1.Text
    QrBox1.Refresh()
End Sub

UserControl的完整代码

QrBox UserControl的完整代码如下:

Imports System.Net
 
Public Class QRBox
    Const _GOOGLE_URL As String = "?chs={WIDTH}x{HEIGHT}&cht=qr&chl={DATA}"
    Dim _DATA As String = String.Empty
 
    Property Data As String
        Get
            Return _DATA
        End Get
        Set(value As String)
            _DATA = value
        End Set
    End Property
 
    Private Function getQRURI() As String
        Dim _qrAddr As String = _GOOGLE_URL.Replace("{WIDTH}", Me.Width.ToString).Replace("{HEIGHT}", Me.Height.ToString)
        _qrAddr = _qrAddr.Replace("{DATA}", WebUtility.UrlEncode(_DATA))
 
        Return _qrAddr
    End Function
 
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)
        If _DATA Is Nothing Then Exit Sub
 
        Dim client As New WebClient()
        Dim bytes() As Byte = client.DownloadData(getQRURI())
        client.Dispose()
 
        Dim memStream As New IO.MemoryStream(bytes)
        Dim bmp As Bitmap = Bitmap.FromStream(memStream)
        memStream.Dispose()
 
        e.Graphics.DrawImage(bmp, 0, 0)
    End Sub
 
    Public Sub New()
        InitializeComponent()
    End Sub
End Class

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c555ec4d1f438fcbf944508189ba22a9.html