Windows11 Notepad cannot find by FindWindowEx in vb.net

138 Views Asked by At

I want to find notepad in Windows 11 by using vb.net source.
But I always get notepad window not found error.
I think Windows 11 notepad is changed style that is the main reason.
It totally work in windows 10.

Here is my code sample.
Please sugguest me.

<System.Runtime.InteropServices.DllImport("user32", SetLastError:=True, CharSet:=Runtime.InteropServices.CharSet.Auto)>
Private Shared Function FindWindowEx(
                                    ByVal hwndParent As Integer,
                                    ByVal hwndChild As Integer,
                                    ByVal lpClassName As String,
                                    ByVal lpWindowName As String) As IntPtr


End Function

Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
        Dim VM_SETTEXT As String = &HCS
        Dim source As String = "hello world"
        Dim p As New Process
        p.StartInfo.FileName = "notepad.exe"       
        p.Start()     
       
        Dim hwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Notepad", "")

        If hwnd <> IntPtr.Zero Then
            MessageBox.Show("Find notepad window")
        End If
End Sub

I want to find Notepad window in Windows 11 to send data to Notepad.

1

There are 1 best solutions below

4
jmcilhinney On

Based on my testing, this:

Dim hwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Notepad", "")

should be this:

Dim hwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Notepad", Nothing)

As you have it, it will only match a window where the caption is an empty string. By specifying Nothing, you tell it to match any caption.

Also, you have declared the first two parameters to be type Integer but then you pass IntPtr values. That will work if you have Option Strict Off but you definitely should not have Option Strict Off, so that should not compile. Either declare the parameters as type IntPtr or pass Integer values. You should set Option Strict On in the project properties and also in the VS options, so it will be On by default for all future projects.