C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


(過去ログ 122 を表示中)
■73201 / )  Re[1]: ImageListにWEB上の画像をセット
□投稿者/ 魔界の仮面弁士 (105回)-(2014/08/28(Thu) 10:54:43)
No73198 (こういち さん) に返信
> 直接できないようなら、PictureBox.LocationでWEB上の画像を取得して、ImageListに追加する、、

Loacation ではなく、ImageLocation ですよね。
Loacation は、PictureBox の座標を示すプロパティです。


ImageLocation プロパティだと、ロードが完了するまでの待ち合わせが行えないため、
PictureBox を使うのであれば、Load メソッドか LoadAsync メソッドの方が良いでしょう。


また、Web サーバーに接続できなった場合や、サーバーには繋がったが
画像形式が不正だった場合のエラーチェックも必要ですね。


Public Class Form1
    Private URL1 As String = "http://www.bing.com/favicon.ico"
    Private URL2 As String = "http://www.google.com/favicon.ico"
    Private URL3 As String = "http://www.yahoo.co.jp/favicon.ico"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        PictureBox1.Hide()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '案1
        Try
            PictureBox1.Load(URL1)
            ImageList1.Images.Add("案1", PictureBox1.Image)

            Button1.ImageAlign = ContentAlignment.MiddleLeft
            Button1.ImageList = ImageList1
            Button1.ImageKey = "案1"
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        '案2
        AddHandler PictureBox1.LoadCompleted, AddressOf Me.LoadCompleted
        PictureBox1.LoadAsync(URL2)
    End Sub
    Private Sub LoadCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
        RemoveHandler PictureBox1.LoadCompleted, AddressOf Me.LoadCompleted

        If e.Error IsNot Nothing Then
            MsgBox(e.Error.Message, MsgBoxStyle.Critical)
            'Return
        End If

        ImageList1.Images.Add("案2", PictureBox1.Image)

        Button2.ImageAlign = ContentAlignment.MiddleLeft
        Button2.ImageList = ImageList1
        Button2.ImageKey = "案2"
    End Sub

    Private Sub Button3_Click(sender As System.Object, e As EventArgs) Handles Button3.Click
        '案3
        Dim wr As System.Net.HttpWebRequest = System.Net.WebRequest.Create(URL3)
        Dim res As System.Net.HttpWebResponse = Nothing
        Try
            res = wr.GetResponse()
            Dim img As Image
            Using stm As System.IO.Stream = res.GetResponseStream()
                img = Image.FromStream(stm)
            End Using
            ImageList1.Images.Add("案3", img)

            Button3.ImageAlign = ContentAlignment.MiddleLeft
            Button3.ImageList = ImageList1
            Button3.ImageKey = "案3"
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Return
        Finally
            If res IsNot Nothing Then res.Close()
        End Try
    End Sub

End Class

返信 編集キー/


管理者用

- Child Tree -