Is it possible to get a form's properties if all you have is a handle?

brainleak

Well-known member
Joined
Dec 20, 2016
Messages
54
Location
Barcelona area
Programming Experience
3-5
Given the handle of another application's window, how do I get its properties, for example the location and size?
 
You would have to use the appropriate Windows API calls, e.g. GetWindowRect. If it's outside your app then you can't just treat it as a .NET object.
Thank you, your suggestion has worked, GetWindowRect yields the coordinates of the window even if it's outside the application:

VB.NET:
Public Class Form1

    Private Structure RECT
        Dim Left As Integer
        Dim Top As Integer
        Dim Right As Integer
        Dim Bottom As Integer
    End Structure

    Private Declare Function GetWindowRect Lib "user32" (ByVal HWND As Integer, ByRef lpRect As RECT) As Integer
    Private Declare Function GetForegroundWindow Lib "user32" () As Integer 
   
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        'To store the handle to a window
        Dim hWnd As System.IntPtr


        'To store the window coordinates
        Dim R As RECT


        'Pause action for 3 sec. to allow user to set focus on another window
        Wait(3)


    'Get handle
        hWnd = GetForegroundWindow()


        'Get coordinates of upper left and lower right corners
        GetWindowRect(hWnd, R)


        Console.WriteLine(R.Left.ToString & " " & R.Top.ToString)
        Console.WriteLine(R.Right.ToString & " " & R.Bottom.ToString)


    End Sub


    Private Sub Wait(sec As Single)
        'Pause sec seconds
        Dim tim As Single


        tim = DateAndTime.Timer
        Do While DateAndTime.Timer < tim + sec
            Application.DoEvents()
        Loop


    End Sub


End Class
 
Back
Top