Find window Height and Width

How to find a focused window Height and width.

it can be any window, for example notepad, mspaint, etc .... I can get a focused window using this code

[DllImport("user32")] 
public static extern IntPtr GetForegroundWindow();

hi f3lix it works, but it returns a value, it depends only on the location. If I change the location, it returns some other values

Kunal it returns msg error .... as refrence object not set

+3
source share
6 answers

I think you need to use user32.dll functions through PInvoke. I'm not sure, but I would do it something like this:

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", SetLastError = true)]
static extern bool GetWindowRect(IntPtr hWnd, out Rectangle lpRect); 


Rectangle rect = new Rectangle();
GetWindowRect(GetForegroundWindow(), out rect);

Note. I have not tried this code, because currently I am not working on Windows ...

:   Rory (. ), , RECT.

[StructLayout(LayoutKind.Sequential)]
public struct RECT {
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

Rectangle RECT .

+7
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);           

public static Size GetControlSize(IntPtr hWnd)
{
    RECT pRect;
    Size cSize = new Size();
    // get coordinates relative to window
    GetWindowRect(hWnd, out pRect);

    cSize.Width = pRect.Right - pRect.Left;
    cSize.Height = pRect.Bottom - pRect.Top;

    return cSize;
}
+1

MDI, :

parentForm.ActiveMDIChild.Size
0

?

  • ?
  • ?

If question 2, use Window.ActualWidthandWindow.ActualHeight

0
source

If your window is inside your application with an MDI application, you can use it with

public static extern IntPtr GetForegroundWindow();

with you try this

int wHeight = Control.FromHandle(GetForegroundWindow()).Height;
int wWidth = Control.FromHandle(GetForegroundWindow()).Width;
0
source

Source: https://habr.com/ru/post/1704638/


All Articles