How To Get The Screen Resolution In Pixels

The function GetWindowRect(), defined in WinUser.h, is able to give the current screen resolution. The declaration of GetWindowRect() is


BOOL
WINAPI
GetWindowRect(
    __in HWND hWnd,
    __out LPRECT lpRect);

We can give a handle to the current desktop window to the above function as input. A sample implementation for getting the current screen resolution is given below.


#include "wtypes.h"
#include <iostream>
using namespace std;

// Get the horizontal and vertical screen sizes in pixel
void GetDesktopResolution(int& horizontal, int& vertical)
{
   RECT desktop;
   // Get a handle to the desktop window
   const HWND hDesktop = GetDesktopWindow();
   // Get the size of screen to the variable desktop
   GetWindowRect(hDesktop, &desktop);
   // The top left corner will have coordinates (0,0)
   // and the bottom right corner will have coordinates
   // (horizontal, vertical)
   horizontal = desktop.right;
   vertical = desktop.bottom;
}

int main()
{       
   int horizontal = 0;
   int vertical = 0;
   GetDesktopResolution(horizontal, vertical);
   cout << horizontal << '\n' << vertical << '\n';
   return 0;
}

About these ads

8 Responses to How To Get The Screen Resolution In Pixels

  1. Paulo Silveira says:

    Thank you!! This piece of code was very helpful.

    Paulo Silveira – Brazil

  2. Wija says:

    Thanks a lot! that’s exactly what i was looking for

  3. Bram says:

    Hi, this is indeed helpful.
    But is there a way to exclude the taskbar in this script?

  4. Fred says:

    Thanks! Been googling for about an hour trying to find how to do that!

  5. Unnamed says:

    Bram: On Windows XP just add 30 to vertical.

  6. Salvatore says:

    Thanks!!

  7. Chlorek says:

    Really usable! Thanks man!

  8. Erwin says:

    Is this also working with multiple displays?
    How to get then the resolution of the two different displays?

    thanks a lot…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: