-1

I am trying to detect whether or not a window is open (and being used by the user). I have used code from this forum but can't get it to work, here is what I've got:

    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

Upon running the program and clicking a button I get "I found the sucker." despite definitely not having a window called "lkhsdlfhslfh" existing let alone open.

How do I fix this?

batv1
  • 131
  • 7
  • I don't think this will fix it, but you should be using `FindWindowW`, not `FindWindowA`. We are a long way away from the mid 1990's so we can safely use the wide-char version. – Andy May 16 '21 at 17:06
  • Also, change the extern definition to return `As IntPtr` instead of `As Long` – Andy May 16 '21 at 17:08

1 Answers1

2

Your method signature is incorrect. It should return IntPtr, not Long.

Try the following:

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

Alternatively, you could use <DllImport>, which is the standard way in .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

Note that unless you're dealing with an ancient program, you should probably use a Unicode charset. This means using FindWindowW (instead of FindWindowA) if you go with Declare or CharSet.Unicode if you go with <DllImport>.

  • Thank you, it worked! One more question, is there a way to make it check if there is a window containing text? For example, with notepad if you have a file open it appends the file name before " - Notepad" – batv1 May 16 '21 at 17:17
  • You may use the [`EnumWindows` function](https://pinvoke.net/default.aspx/user32.EnumWindows) for that. See [this answer](https://stackoverflow.com/a/20276701/8967612) for a usage example. The code is in C# but the idea is the same. – 41686d6564 stands w. Palestine May 16 '21 at 17:32