我正在使用此代码来检测特定窗口何时处于活动状态,以及何时将句柄保存在变量中:
Dim kiosk As IntPtr
Dim l As Integer = GetWindowTextLength(GetForegroundWindow())
Dim WindowTextBuffer As String = New String(Chr(0), l)
GetWindowText(GetForegroundWindow(), WindowTextBuffer, l + 1)
Debug.WriteLine(WindowTextBuffer)
If WindowTextBuffer = "FFKiosk" Then
kiosk = GetForegroundWindow()
End If
到目前为止一切正常。但我想验证此窗口是否仍处于活动状态,如果不是,我想将kiosk变量设置为null。如何验证此句柄是否仍然有效?
答案 0 :(得分:1)
嗯,您的具体问题的答案是:从User32.dll导入IsWindow函数
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True)> _
Public Shared Function IsWindow(ByVal hWnd As IntPtr) As Boolean
End Function
然后,
If IsWindow(kiosk) Then
' do something
End If
但MSDN warns against that如果您的线程不是创建窗口的线程:“一个线程不应该使用IsWindow作为它的窗口 没有创建,因为窗口可能会在此之后被销毁 功能被称为。此外,因为窗户把手被回收了 句柄甚至可以指向不同的窗口。“
相反,最好获取进程ID并检查进程是否仍在运行。
Dim processes As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("theExeName")
Dim processIds(processes.Length) As Integer
If processes.Length > 0 Then
Dim i As Integer = 0
For Each processId As Integer In processIds
processIds(i) = processes(i).Id
Next