How to get width and height from CreateWindowEx()

2019-04-21 03:39发布

问题:

I have made a window with CreateWindowEx() function, now how do i get the width and height from that window i created? This sounds very basic thing to do, but i just couldnt find any answer ;_;

This is needed because the window height is created automatically depending on how the Windows wants to create it.

Language C or C++

回答1:

Use GetWindowRect. Subtract the right from the left to get the width and the bottom from the top to get the height.

RECT rect;
if(GetWindowRect(hwnd, &rect))
{
  int width = rect.right - rect.left;
  int height = rect.bottom - rect.top;
}

As a side note, if you'd like the client area instead of the entire window. You can use GetClientRect. For other information about the window you can use GetWindowInfo.



回答2:

Have you tried GetWindowRect() or GetWindowInfo() which returns a WINDOWINFO structure?



回答3:

I believe you're looking for GetWindowInfo

Example:

HWND window = ::CreateWindowEx(...);
WINDOWINFO info;
if ( ::GetWindowInfo(window, &info) ) {
  ...
}


回答4:

Given there's no indication why you need the size, and that the size can change if the window style is set to include resizable attributes [and the user resizes the window using minimize/maximize/restore or drags a window edge], your safest choice is to include a message handler for WM_SIZE and use the wparam and lparam parameter values to determine window dimensions. This way, you'll always know the current size. WM_SIZE is called in the sequence of messages post window creation.