Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 如何检测另一个应用程序的窗口是否打开?_Vb.net_Winforms - Fatal编程技术网

Vb.net 如何检测另一个应用程序的窗口是否打开?

Vb.net 如何检测另一个应用程序的窗口是否打开?,vb.net,winforms,Vb.net,Winforms,我试图检测用户是否打开并正在使用窗口。我使用了来自论坛的代码,但无法使其工作,以下是我得到的: Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _ (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Sub btnCheckWindow_Click(s

我试图检测用户是否打开并正在使用窗口。我使用了来自论坛的代码,但无法使其工作,以下是我得到的:

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

    Private Sub btnCheckWindow_Click(sender As Object, e As EventArgs) Handles btnCheckWindow.Click
        Dim lngFindIt As Long
        lngFindIt = FindWindow(vbNullString, "lkhsdlfhslfh")
        If lngFindIt = 0 Then
            MsgBox("It is not here")
        Else
            MsgBox("I found the sucker.")
        End If
    End Sub
在运行程序并点击按钮后,我找到了吸盘。尽管目前还没有一个名为lkhsdlfhslfh的窗口,更不用说打开了


如何修复此问题?

您的方法签名不正确。它应该返回IntPtr,而不是Long

请尝试以下操作:

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
    (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr

Private Sub btnCheckWindow_Click(sender As Object, e As EventArgs) Handles btnCheckWindow.Click
    Dim result As IntPtr= FindWindow(Nothing, "lkhsdlfhslfh")
    If result = IntPtr.Zero Then
        MsgBox("Window not found.")
    Else
        MsgBox("Found it.")
    End If
End Sub
或者,您可以使用,这是.NET中的标准方式:

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Private Shared Function FindWindow(
 ByVal lpClassName As String,
 ByVal lpWindowName As String) As IntPtr
End Function

请注意,除非您处理的是一个古老的程序,否则您可能应该使用Unicode字符集。这意味着如果使用Declare或CharSet.Unicode,则使用FindWindowW而不是FindWindowA。

我认为这不会解决问题,但应该使用FindWindowW,而不是FindWindowA。我们离20世纪90年代中期还有很长的路要走,所以我们可以安全地使用宽字符版本。另外,将外部定义更改为返回IntPtr而不是LongThank you,它成功了!还有一个问题,有没有办法让它检查是否有包含文本的窗口?例如,使用记事本,如果您打开了一个文件,它会在-notepad之前附加文件名,您可以使用。有关用法示例,请参见。代码是用C编写的,但思想是一样的。