アクティブウインドウのウインドウ名取得をしたい。
Windowsアプリが数個実行されている時に、そのアクティブなウィンドウを取得したいわけです。
vb6で作ったと思われる物を参考にVB2008に変換しようとして
います。ここの掲示板も参考に、下の様に書いて見ました。
実行すると。
(現在アクテイブウインドウのタイトル名は)
までのみ表示されます。
また下のコードの中で
('現在、アクティブウインドウは自アプリなので自分自身を表示)と
書いているところの意味がわかりにくいのですが。
作ろうとしているのは、フォームのボタンはmousemoveを使用して
プログラムを実行するので、他のアプリがアクティブになったままの
状態で、どのアプリがアクティブになっているかを取得出来る物と
思ってます。
どうぞよろしく御願いします。
Public Class Form1
'フォームの頭で宣言して下さい(General Declarations)
Private Declare Function GetActiveWindow Lib "USER32" () As Long
Private Declare Function GetWindowText Lib "USER32" Alias "GetWindowTextA" _
(ByVal hWnd&, ByVal lpString$, ByVal cch&) As Long
Private Sub Button1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseMove
Dim rtn, rtn2 As Long
Dim Name As String
Dim Leng As Long
'バッファを確保
Name = New String(CChar(vbNullChar), 250)
Leng = Len(Name)
'アクティブウインドウのハンドル取得
rtn = GetActiveWindow()
'アクティブウインドウのウインドウ名取得
rtn2 = GetWindowText(rtn, Name, Leng)
'現在、アクティブウインドウは自アプリなので自分自身を表示
MsgBox("現在アクテイブウインドウのタイトル名は" & Name & "です")
End Sub
End Class
いろいろと間違っていますよ。
その Declare で As Long を使うべきでは無いですし、
文字列処理も 〜A 系ではない方が望ましいです。
> フォームのボタンはmousemoveを使用して
MouseMove の最中に MsgBox を呼び出すのは、都合が悪くありませんか?
> Declare Function GetActiveWindow
GetActiveWindow は自スレッド内のアクティブウィンドウを得るものなので、
実質、ActiveForm の Handle プロパティを得るような意味になってしまいます。
別アプリのウィンドウを得たいのであれば、GetForegroundWindow API を
試してみてください。たとえばこんな感じです。
Public Class Form1
Private Declare Function GetForegroundWindow Lib "user32" () As IntPtr
Private Declare Auto Function GetWindowText Lib "user32" _
(ByVal hWnd As IntPtr, _
ByVal lpString As System.Text.StringBuilder, _
ByVal cch As Integer) As Integer
Private Sub Button1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Button1.MouseMove
Dim title As New System.Text.StringBuilder(256)
Dim hWnd As IntPtr = GetForegroundWindow()
If Not (IntPtr.Zero.Equals(hWnd) OrElse Me.Handle.Equals(hWnd)) Then
Dim ret As Integer = GetWindowText(hWnd, title, 256)
DirectCast(sender, Control).Text = title.ToString(0, ret)
End If
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MsgBox(DirectCast(sender, Control).Text)
End Sub
End Class
おっしゃるとおりです。たいへん有り難う御座いました。
編集 削除