サンプルプログラム

Yahooで検索する

Yahooのサイトを開き、検索窓にキーワードを入力し、検索ボタンを押します。

Public Class FrmSampleIE

    Private objIE As SHDocVw.InternetExplorer

    Private Sub FrmSampleIE_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'IEの起動
        objIE = CreateObject("InternetExplorer.Application") 'オブジェクトを作成
        objIE.Navigate("about:blank") '空ページの表示
        objIE.Visible = True 'IEを表示
    End Sub

    Private Sub FrmSampleIE_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        If Not objIE Is Nothing Then
            objIE.Quit()
        End If
    End Sub

    Public Function OpenWebWait() As Boolean

        Try
            '読み込み完了まで待つ
            Do While objIE.Busy OrElse _
                objIE.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE

                '無処理
                System.Windows.Forms.Application.DoEvents()
                System.Threading.Thread.Sleep(100)
            Loop

            Return True

        Catch ex As Exception
            Return False
        End Try

    End Function

    Private Sub btnYahooSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYahooSearch.Click

        'Yahooを開く
        objIE.Navigate("http://yahoo.co.jp")
        OpenWebWait()

        'キーワードを入力し、クリック
        objIE.Document.GetElementById("srchtxt").InnerText = "プログラム ネットサーフィン"
        objIE.Document.GetElementById("srchbtn").Click()

    End Sub

End Class
Public Class FrmSampleWeb

    Private Sub btnYahooSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYahooSearch.Click

        'Yahooを開く
        WebBrowser1.Navigate("http://yahoo.co.jp")
        OpenWebWait()

        'キーワードを入力し、クリック
        WebBrowser1.Document.GetElementById("srchtxt").InnerText = "プログラム ネットサーフィン"
        WebBrowser1.Document.GetElementById("srchbtn").InvokeMember("Click")

    End Sub

    Public Function OpenWebWait() As Boolean

        Try
            '2秒間ほど待機
            System.Threading.Thread.Sleep(2000)

            '読み込み完了まで待つ
            Do While (WebBrowser1.IsBusy OrElse _
                WebBrowser1.ReadyState <> WebBrowserReadyState.Complete)

                '無処理
                System.Windows.Forms.Application.DoEvents()
                System.Threading.Thread.Sleep(100)
            Loop

            Return True

        Catch ex As Exception
            Return False
        End Try

    End Function

End Class
  • デザイナでボタンを配置し、名前を「btnYahooSearch」とします。