C windows screen size

How you go about getting the screen resolution is dependent on the operating system and/or hardware you’re using. There is no concept of screen resolution in the C standard library.

  • If you’re running an operating system, you could use the API function(s) provided by the operating system to obtain the screen resolution.
  • If you’re not running anyoperating system, you would have to get this information from device registers, which are either memory-mapped or attached to I/O ports.
  • If you’re using third-party library to abstract the operating system or the hardware, you would use whatever mechanism the library provides to obtain this information.

If you’re running a modern version of Windows (Windows 2000, Windows XP, or later), and you don’t want to use a third-party library, you can use the Windows API functions GetDesktopWindow and GetWindowRect to get the current screen resolution:

#include <windows.h>
#include <stdio.h>
#include <stdbool.h>

// This function will return the horizontal
// and vertical screen resolution in pixels. 
// The function returns true on success, false otherwise.

bool GetDesktopResolution(int *pHorizontal, int *pVertical)
{
    bool status = false;

    // We'll need a RECT (rectangle) structure to receive the info.
    RECT desktopRectangle;

    // We'll also need an HWND (handle) to the Windows desktop. 
    const HWND desktopHandle = GetDesktopWindow();

    // If we got a handle, and we can get the rectangle
    // structure filled in, then report the resolution values 
    // to the caller through the parameters.

    if (desktopHandle && GetWindowRect(desktopHandle, &desktopRectangle))
    {
        // The left and top values of the rectangle are 0 and 0.
        // We're interested in the right and bottom values.
        *pHorizontal = desktopRectangle.right;
        *pVertical = desktopRectangle.bottom;

        // Ensure we report success to the caller.
        status = true;
    }

    return status;
}

// The following demonstrates how to use the
// GetDesktopResolution function.

int main(void)
{
    int horizontalResolution;
    int verticalResolution;

    if (GetDesktopResolution(&horizontalResolution, &verticalResolution))
    {
        printf("Screen resolution is %d x %d.\n", 
        horizontalResolution, verticalResolution);
    }

    return 0;
}

On a Windows system with a current display resolution setting of 1920 x 1080, running the above program would display:

Screen resolution is 1920 x 1080.

Keep in mind that the user and other APIs can change the screen resolution, and that this code will report whatever the current screen resolution is. This might not be the maximum supported resolution or the native screen resolution.

Распределенное обучение с TensorFlow и Python

AI_Generated 05.05.2025

В машинном обучении размер имеет значение. С ростом сложности моделей и объема данных одиночный процессор или даже мощная видеокарта уже не справляются с задачей обучения за разумное время. Когда. . .

CRUD API на C# и GraphQL

stackOverflow 05.05.2025

В бэкенд-разработке постоянно возникают новые технологии, призванные решить актуальные проблемы и упростить жизнь программистам. Одной из таких технологий стал GraphQL — язык запросов для API,. . .

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

Rectangle ^ClientResolution = gcnew Rectangle();

ClientResolution = Screen::GetBounds();          

float CurrentWidth = 1366 ;
float CurrentHeight = 768;

float RatioWidth = ((float)ClientResolution->Width / (float)CurrentWidth );

float RatioHeight =((float)ClientResolution->Height / (float)CurrentHeight);

	this->Scale(RatioWidth,RatioHeight);

error C2661: ‘System::Windows::Forms:: Screen::GetBounds’ : no overloaded function takes 0 arguments

Any help would be much appreciated.

Edited by sheennave because: .

jonsca 1,059 Quantitative Phrenologist Team Colleague Featured Poster

Try changing line 3 to ClientResolution = Screen::GetBounds(this->ClientRectangle); You need to give GetBounds a rectangle or a control so it can give you back the resolution of the screen showing that object, so give it the rectangle of the form.

Thanks. The code works but it did not make sense. The application still have a screen size or resolution problem . Maybe you have another bright idea ?

jonsca 1,059 Quantitative Phrenologist Team Colleague Featured Poster

The code works but it did not make sense. The application still have a screen size or resolution problem.

You’re going to have to elaborate on what you mean by those two statements.

You’re going to have to elaborate on what you mean by those two statements.

Dear jonsca ,
The syntax of the code was corrected by your help.Then I tested the app on a desktop which has 1024 X 768 screen res. As a result I saw that the forms are all maximized unnecessarily.i’m afraid that the syntax of the code passed but semantically failed .

Edited by sheennave because: n/a

jonsca 1,059 Quantitative Phrenologist Team Colleague Featured Poster

What did the ClientResolution return for values?

Also, that overload of Scale has been obsolete since before .NET 2.0 (according to MSDN) so you might want to try the overload that takes a SizeF object. I don’t know if the results will be any better, but there must be some reason it was deprecated.

What did the ClientResolution return for values?

ClientResolution is 1024 by 768 pixel

You’re right there are some obsolote points -everwhere-, but still we can not say it is a compiler bug or not. However please let me know some more about your idea then i would try

Edited by sheennave because: n/a

jonsca 1,059 Quantitative Phrenologist Team Colleague Featured Poster

Where is current resolution coming from, is that the size of your form’s window? What do you want to happen to it (shrink if it’s too big?) I don’t mean to seem dense in asking you these questions, it’s just I’m sure it’s not a compiler bug, you’ve probably just got the ratios flipped over.

Good proposal jonsca, i need to get the compiler to apply…

The code below urges the form windows to stay stable on client machines which have different resolutions. This is for Daniweb users.

float ClientWidthF = 1280;   // clients upper width
float ClientHeightF = 1024;  // clients upper height

float CurrentWidthF  = System::Windows::Forms::SystemInformation::PrimaryMonitorSize.Width; // 1024 average

float CurrentHeightF = System::Windows::Forms::SystemInformation::PrimaryMonitorSize.Height; // 768 average

float OranWidthF = ((float)ClientWidthF / (float)CurrentWidthF );  

float OranHeightF =((float)ClientHeightF / (float)CurrentHeightF);  

width->Text = Convert::ToString(OranWidthF);    // optimal in this case
height->Text = Convert::ToString(OranHeightF); 

this->Scale(OranWidthF,OranHeightF); 
this->CenterToScreen();

Special thanks goes to jonsca . Thank you .

Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.

How to get the size of the screen, without the taskbar?

I’m pretty surprised that it seems like no one has asked this question before. So how do you get the RECT of the monitor, without the taskbar? This

1
2
RECT rcScreen;
GetWindowRect(GetDesktopWindow(), &rcScreen);

Gets the RECT of the screen with it, but how do you get it without?

Are you wanting the size of the window’s client area?

Use the GetClientRect() API function.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633503%28v=vs.85%29.aspx

The size of a window is more than just the client area + the caption area/title bar. There is the size of:

1. if present the menu bar

2. the size/thickness of the window frame, x 2. (top and bottom, left and right). This can vary depending of the window is sizable or static sized.

3. if present the size of the scroll bar, horizontal and vertical

4. if present the size/thickness of a 3D border.

5. if present the size of toolbars, dockable or static.

6. if present the size of a status bar.

There might be other non-client parts of a window I forgot, the 6 I mentioned are the most common that change the size of the client area.

To find out the usable area of the desktop window you use the GetSystemMetrics() API function with SM_CXFULLSCREEN and SM_CYFULLSCREEN. SM_CYFULLSCREEN would return the height of the desktop without the height of the taskbar, if the taskbar is at the bottom or top of the desktop. Some people move their taskbar to the left or right of the screen.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385%28v=vs.85%29.aspx

Last edited on

To obtain the size of the desktop (the work area), without just the taskbar, you can use GetSystemMetrics() API function.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385%28v=vs.85%29.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <windows.h>

int main()
{
   // size of screen (primary monitor) without taskbar or desktop toolbars
   std::cout << GetSystemMetrics(SM_CXFULLSCREEN) << " x " << GetSystemMetrics(SM_CYFULLSCREEN) << "\n";

   // size of screen (primary monitor) without just the taskbar
   RECT xy;
   BOOL fResult = SystemParametersInfo(SPI_GETWORKAREA, 0, &xy, 0);
   std::cout << xy.right - xy.left << " x " << xy.bottom - xy.top << "\n";

   // the full width and height of the screen (primary monitor)
   std::cout << GetDeviceCaps(GetDC(NULL), HORZRES) << " x " << GetDeviceCaps(GetDC(NULL), VERTRES) << "\n";
}

Topic archived. No new replies allowed.

6

Answers

Edward Aymami

1y

709


1

I need to find out the screen size of any computer that my application is running on. I want to center my forms without using the whole screen. I am using Visual Studio to develop this application. I have looked at MS docs but there are now examples of how or where to execute the comomand. I need both Horizontal and Vertical numbers.

Any help would be greatly appreciated.

Answers (6)

Next Recommended Forum

cast to value type ‘System.Int32’ failed because the materialized

asp.net sql command quries or store procedure name

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Os prober не видит windows 10
  • Как удалить папку через консоль windows 10
  • Настройка http сервера на windows 10
  • Код ошибки 651 при подключении к интернету windows 10
  • Windows 10 для слабых компьютеров torrent