Vb.net 如何获取连接到最顶端窗口的应用程序?

Vb.net 如何获取连接到最顶端窗口的应用程序?,vb.net,Vb.net,我的VB.NET应用程序用于监视最顶部窗口中当前正在运行的应用程序。我使用计时器尝试了以下方法: Declare Function GetActiveWindow Lib "user32" () As System.IntPtr Declare Function GetForegroundWindow Lib "user32" () As System.IntPtr Public Declare Auto Function GetWindowText Lib "user32" _ (ByVal

我的VB.NET应用程序用于监视最顶部窗口中当前正在运行的应用程序。我使用计时器尝试了以下方法:

Declare Function GetActiveWindow Lib "user32" () As System.IntPtr
Declare Function GetForegroundWindow Lib "user32" () As System.IntPtr
Public Declare Auto Function GetWindowText Lib "user32" _
(ByVal hWnd As System.IntPtr, _
ByVal lpString As System.Text.StringBuilder, _
ByVal cch As Integer) As Integer 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
   Dim Caption As New System.Text.StringBuilder(256)
   Dim hWnd As IntPtr = GetForegroundWindow()
   GetWindowText(hWnd, Caption, Caption.Capacity)
   'Caption now holds the title of the topmost window
End Sub 
通过这一点,我可以看到,例如Outlook或Internet Explorer是最顶部的窗口,因为名称位于窗口的标题栏中。但是,如果用户在Outlook中装箱一封新邮件,则窗口的标题为“无标题邮件”,没有提示窗口中正在运行什么应用程序

如何获取连接到最顶端窗口的应用程序?p>


谢谢你的帮助

您需要pinvoke GetWindowThreadProcessId()。这将获取拥有该窗口的进程的ID。回到托管代码,Process.GetProcessById()提供了流程的详细信息