locked
FAQ Item: How to retrieve a Window Handle in Visual Basic.NET?

    Question

  • How to retrieve a Window Handle in Visual Basic.NET?


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Monday, February 01, 2010 3:16 PM

Answers

  • In many Windows Programming scenarios, we need a Window Handle to perform some tasks, like:

    1. Send specified messages to the window,

    2. Retrieve/Modify the text of the window,

    3. Subclass the window to change its behaviors,

    , and so on…

     

    If the window is in our .NET Winform application, we can get its handle directly via Control.Handle property,

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(VS.80).aspx

     

    If the window is from another native application, to get its handle, we have to call the Windows APIs FindWindow and FindWindowEx.

     

    FindWindow function is used to retrieve a handle of a top-level window whose class name and window name match the specified strings.

    http://msdn.microsoft.com/en-us/library/ms633499(VS.85).aspx

    FindWindowEx function can be used to find children windows of a specified parent window.

    http://msdn.microsoft.com/en-us/library/ms633500(VS.85).aspx

     

    The followings are Visual Basic.NET P/Invoke declarations for the two WinAPIs,

    ---------------------------------------------------

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _

    Private Shared Function FindWindow( _

         ByVal lpClassName As String, _

         ByVal lpWindowName As String) As IntPtr

    End Function

     

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _

    Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _

                          ByVal childAfter As IntPtr, _

                          ByVal lclassName As String, _

                          ByVal windowTitle As String) As IntPtr

    End Function

    ----------------------------------------------------

     

    Codes:

    Dim toplevelWindow as IntPtr = FindWindow(“classname”, ”windowcaption”)

    Dim childWindow as IntPtr = FindWindowEx(toplevelWindow, new IntPtr(0), “classname”, “windowcaption”)

     

     

    Related Threads:

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/1a4c6def-a24b-4a72-8ce5-eaa00c6182f0/

    http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/3ee8d5f9-b6d3-43c7-b486-dcb92b2edfea/
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Monday, February 01, 2010 3:17 PM