毎週、いろいろと質問させていただいているJJJです。
前回、「マウスホバー機能を用いた、マウスポイントが触れた文字を1文字または1文ごとにテキストに移動させるには。」で、魔界の弁士さんに解決していただきありがとうございました。
今回は、自分なりにオンマウスオーバーを利用して、画像のAltタグに描かれている内容文字をテキストボックスに移動したい思ったのですが、下記のように書き方でよろしいのでしょうか。
Imports System.Runtime.InteropServices.Marshal
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.google.co.jp/")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Document.AttachEventHandler("onmouseover", AddressOf document_onmouseover)
End Sub
Sub document_onmouseover(ByVal sender As Object, ByVal e As EventArgs)
TextBox1.Text = WebBrowser1.Document.GetElementFromPoint(WebBrowser1.PointToClient(Control.MousePosition)).InnerHtml
End Sub
End Class
上記の状態だと、HTMLの内容を全てテキストボックスに移動してしまい、Altの内容だけとはいかないのです。
どなたか、ご尽力をお願いいたします。
HTMLの文を抽出できているので下記のような
alt=○○○○
の○○○○の部分だけをテキストボックスに入れるにはどのようにすればいいのでしょうか。
正規表現などを用いたほうがいいのでしょうか。
GetElementFromPoint で取得できるのは HtmlElement オブジェクトですよね、と前置き。
alt も属性の一つですから、HtmlElement から属性取得メソッドを呼べば良いでしょう。
Hongliangさん、お返事ありがとうございます。
Imports System.Runtime.InteropServices.Marshal
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.google.co.jp/")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
WebBrowser1.Document.AttachEventHandler("onmouseover", AddressOf document_onmouseover)
End Sub
Sub document_onmouseover(ByVal sender As Object, ByVal e As EventArgs)
TextBox1.Text = WebBrowser1.Document.GetElementFromPoint(WebBrowser1.PointToClient(Control.MousePosition)).InnerHtml
Dim Elements As HtmlElementCollection = Me.WebBrowser1.Document.GetElementsByTagName("img")
For Each Element As HtmlElement In Elements
If Element.GetAttribute("alt") = "img" Then
TextBox1.Text = Element.TagName
End If
Next
End Sub
End Class
こんな感じの考えたでよいのでしょうか。
HtmlElement から属性取得メソッドを呼び出すというのが、いまいちよく分かっていません。
申し訳ないです。もう少し、自分なりに考えて書いてみたいと思います。
DOMのイベントを使うのではなく,VB2005なら普通にイベントを使った方がよいと思います。
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.google.co.jp/")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim Document As HtmlDocument = DirectCast(sender, WebBrowser).Document
AddHandler Document.MouseOver, AddressOf Document_MouseOver
End Sub
Sub Document_MouseOver(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
TextBox1.Text = e.ToElement.GetAttribute("alt")
End Sub
End Class
YASさん、ありがとうございました。
問題はすべて解決いたしました。
今後も、VBの勉強に励んでいこうと思います。
ツイート | ![]() |