RV.
RV.

Reputation: 2842

find window Height & Width

how to find focused window Height & Width ..

it might be any windows window like notepad,mspaint etc... i can get the focused window by help of this code

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

hi f3lix it's working but it's return the value depends on the location only.. if i change the location it's return some other values

Kunal it's return error msg....like object refrence not set

Upvotes: 6

Views: 24596

Answers (5)

Balaji Annamalai
Balaji Annamalai

Reputation: 21

[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;
}

Upvotes: 2

dommer
dommer

Reputation: 19810

If you're building an MDI app, you could use:

parentForm.ActiveMDIChild.Size

Upvotes: 0

Kunal S
Kunal S

Reputation: 97

If your window is inside your aplication, having an MDI app, you might use this, having

public static extern IntPtr GetForegroundWindow();

with you, try this

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

Upvotes: 0

f3lix
f3lix

Reputation: 29879

I think you have to use user32.dll functions via PInvoke. I'm not sure, but I would do it somewhat 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 did not try this code, because I am currently not working on Windows...

EDIT: Rory pointed out to me (see comments) that we can't use the standard Rectangle here and we need to define our own RECT.

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

Don't forget to replace Rectangle with RECT in the first piece of code.

Upvotes: 10

Frances
Frances

Reputation:

What exactly is your question?

  1. How to get the focused window?
  2. How to get the width and height of a Window?

If question 2, use Window.ActualWidth and Window.ActualHeight

Upvotes: 0

Related Questions