System windows forms screen primaryscreen bounds

Hello
  • Remove From My Forums
  • Question

  • Hello

    I have a simple windows form application (single windows form for test) that works fine for 1600×900 resolution however doesn’t work for 1920×1080 resolution. All I do is capture mouse click and convert point to screen coordinate using PointToScreen.

    When I checked Screen.PrimaryScreen.Bounds for 1600×900, I get correct values for Width and Height i.e. width = 1600 and height = 900. However for 1920×1080 I get Screen.PrimaryScreen.Bounds.Height = 1536 and Width= 864. Any idea what’s going on wrong?

    Thanks  

Answers

  • Hello

    I have a simple windows form application (single windows form for test) that works fine for 1600×900 resolution however doesn’t work for 1920×1080 resolution. All I do is capture mouse click and convert point to screen coordinate using PointToScreen.

    When I checked Screen.PrimaryScreen.Bounds for 1600×900, I get correct values for Width and Height i.e. width = 1600 and height = 900. However for 1920×1080 I get Screen.PrimaryScreen.Bounds.Height = 1536 and Width= 864. Any idea what’s going on wrong?

    Thanks  

    Hi,

    You could use WorkingArea which returns desktop area of the display,
    excluding taskbars, docked windows, and docked tool bars instead, since that issue may due to these areas.

    System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height 
    

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Proposed as answer by

      Sunday, July 6, 2014 5:29 PM

    • Marked as answer by
      Barry Wang
      Tuesday, July 8, 2014 3:23 AM

I’m trying to convert the windows application to wpf application, and everything is fine but i was Struck at this point converting the bellow declaration not working out in code of wpf.

these are windows declarations,

Dim screenwidth As String = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width

Dim screenheight As String = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height

i googled to find the equivalent class properties for these declarations and i got some thing, but those are existing but not working at the point of time i’m trying to use them at

«PointToScreen(New Point(0,0))»
they are:

If i use these in my code:

Dim screenwidth As String = System.Windows.SystemParameters.VirtualScreenWidth
Dim screenheight As String = System.Windows.SystemParameters.VirtualScreenHeight
‘(OR)

Dim screenwidth As String = System.Windows.SystemParameters.PrimaryScreenWidth
Dim screenheight As String = System.Windows.SystemParameters.PrimaryScreenHeight

       With MyPanel
            .PointToScreen(New Point(SystemParameters.VirtualScreenWidth, 0)) ' Getting Exception in this line               
            .Height = (80 / 1080) * screenheight
            .Width = screenwidth                
            .Background = New SolidColorBrush(Colors.Transparent)
        End With

Am getting the exception as Invalid Operation Exception saying that
«The visual is not connected to PresentationSource.»

i alreadt tried this post http://social.msdn.microsoft.com/Forums/en/wpf/thread/f3c982a1-ca16-4821-bf08-f6dd8ff8d829
, but i want to try it out using PointToScreen only.

How can i resolve this ????
Please help me

Posted by: Suprotim Agarwal ,
on 11/14/2007,
in Category WinForms & WinRT

Abstract: In this article, we will see how to programmatically center the form using the Screen.PrimaryScreen.Bounds property. We will also use the FormWindowState to Maximize and Minimize the form.

How to programmatically maximize, minimize and center the form

One of the frequently asked questions about Windows Forms 2.0 is to change the position of the forms at runtime or to maximize/minimize the form. In this article, we will see how easy it is to do so.

Center the Form

The Form.StartPosition sets the starting position of the form at runtime. However the resolution and size of the client machine varies. That is one of the reasons that the default value of StartPosition is ‘WindowsDefaultLocation’ which automatically calculates the position based on the resolution.

One way to center the form is set the StartPosition property to ‘CenterScreen’. However, in order to programmatically set the form’s position to center, follow these steps:

Step 1: Drag and drop a button on the form. Rename it to btnCenter

Step 2: On the button click event, add the following code :

C#

private void btnCenter_Click(object sender, EventArgs e)

{

      int boundWidth = Screen.PrimaryScreen.Bounds.Width;

      int boundHeight = Screen.PrimaryScreen.Bounds.Height;

      int x = boundWidth — this.Width;

      int y = boundHeight — this.Height;

      this.Location = new Point(x / 2, y / 2);

}

VB.NET

Private Sub btnCenter_Click(ByVal sender As Object, ByVal e As EventArgs)

       Dim boundWidth As Integer = Screen.PrimaryScreen.Bounds.Width

       Dim boundHeight As Integer = Screen.PrimaryScreen.Bounds.Height

       Dim x As Integer = boundWidth — Me.Width

       Dim y As Integer = boundHeight — Me.Height

       Me.Location = New Point(x / 2, y / 2)

End Sub

The Screen.PrimaryScreen.Bounds gets the bounds of the display screen. The width and height of the display is subtracted with the width and height of the form. Once we get this calculated value, set the location by passing the value to Point().

Maximize the Form

Step 1: Drag and drop a button on the form. Rename it to btnMax

Step 2:  On the click event, write the following code :

C#

 private void btnMax_Click(object sender, EventArgs e)

{

      this.WindowState = FormWindowState.Maximized;

}

VB.NET

Private Sub btnMax_Click(ByVal sender As Object, ByVal e As EventArgs)

Me.WindowState = FormWindowState.Maximized

End Sub

Minimize the Form

Step 1: Drag and drop a button on the form. Rename it to btnMin

Step 2: On the click event, write the following code:

C#

private void btnMin_Click(object sender, EventArgs e)

{

      this.WindowState = FormWindowState.Minimized;

}

VB.NET

Private Sub btnMin_Click(ByVal sender As Object, ByVal e As EventArgs)

      Me.WindowState = FormWindowState.Minimized

End Sub

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Проверенное и простое решение

Я искал ответ на этот вопрос в SO и некоторых других сайтах, но один ответ был для меня очень сложным, а некоторые другие ответы просто не работают правильно, поэтому после большого тестирования кода я решил эту головоломку.

Примечание: я использую Windows 8 и моя панель задач не находится в режиме автоматического скрытия.

Я обнаружил, что установка WindowState на Normal перед выполнением каких-либо изменений остановит ошибку с непокрытой панелью задач.

Код

Я создал этот класс с двумя методами, первый входит в «полноэкранный режим», а второй выходит из «полноэкранного режима». Итак, вам просто нужно создать объект этого класса и передать форму, которую вы хотите установить в полноэкранном режиме, в качестве аргумента методу EnterFullScreenMode или методу LeaveFullScreenMode:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Пример использования

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

Я поместил тот же ответ на другой вопрос, и я не уверен, является ли он дубликатом или нет. (Ссылка на другой вопрос: Как отобразить форму Windows в полноэкранном режиме поверх панели задач?)

Бывает много ситуаций, когда необходимо сделать снимок экрана, на пример при поддержке установленного программного обеспечения снимок экрана может очень сильно помочь в описании проблемы.

В этой статье мы рассмотрим как сделать снимок экрана, отобразить его, а так же сохранить на диск.

В далекие времена .NET Framework 1.0, что бы сделать снимок экрана приходилось прибегать к вызову Windows API. В .NET Framework 2.0 в пространстве имен System.Drawing и System.Drawing.Imaging появляются новые классы, которые, благодаря GDI+, позволяют работать с графикой, используя только .NET.

Для демонстрации создадим простую Windows Forms программу, которая будет получать снимок экрана, отображать его на форме, а так же при необходимости сохранять его в виде графического файла.

Разместим на форме 4-е кнопки с именами btnCapture, btnSaveJpg, btnSavePng, btnClose, один PictureBox с именем img, а так же SaveFileDialog с именем dlg.

Перейдем к коду, нам потребуется подключить пространства имен

System.Drawing и System.Drawing.Imaging.
 
using System.Drawing;
using System.Drawing.Imaging;

Теперь нам понадобится объект Bitmap (растровое изображение), который будет использоваться для хранения снимка экрана, но т.к. он будет нужен как при самом получении изображения, так и при сохранении изображения, то лучше его сделать частью класса frmMain.

public partial class frmMain : Form
{
    private Bitmap captured;
 
    public frmMain()
    {
        InitializeComponent();
    }
...

Далее создадим процедуру получения снимка экрана по нажатию на кнопку btnCapture. Во первых необходимо определить размер создаваемого изображения, а так же глубину цвета. Эти данные можно получить из свойств объекта Screen. В примере будет использоваться основной экран, что для варианта с одним монитором вполне годится, а в случае с несколькими мониторами необходимо использовать массив Screen.AllScreens[].

Размер изображения:

Rectangle bounds = Screen.PrimaryScreen.Bounds;

Глубина цвета – это количество бит, выделяемых на каждую точку на экране, что в свою очередь определяет количество цветов, которое может принимать эта точка. Для минимизировать использование памяти будем использовать полученное значение для создания растрового изображения:

int colourDepth = Screen.PrimaryScreen.BitsPerPixel;

Что бы использовать полученное значение глубины цвета, необходимо создать объект RixelFormat, который представляет из себя перечисление и присвоить ему соответствующее значение. Существует некоторое ограничение для значения в 8-мь бит, по этому для таких снимков экрана будет создаваться 16-и битное изображение.

PixelFormat format;
switch (colourDepth)
{
    case 8:
    case 16:
        format = PixelFormat.Format16bppRgb565;
        break;
 
    case 24:
        format = PixelFormat.Format24bppRgb;
        break;
 
    case 32:
        format = PixelFormat.Format32bppArgb;
        break;
 
    default:
        format = PixelFormat.Format32bppArgb;
        break;
 
}

Теперь, зная значение глубины цвета и размера изображения, можно инициализировать объект bitmap, которому ранее было присвоено имя captured:

captured = new Bitmap(bounds.Width, bounds.Height, format);

Переходим к использованию GDI+, создадим поверхность для рисования, которая будет связана с нашим растровым изображением.

Graphics gdi = Graphics.FromImage(captured);

Ну и наконец сделаем снимок экрана, в этом нам поможет метод CopyFromScreen, в него передаются 5-ть параметров, первые два это координаты левого верхнего пикселя копируемого изображения, следующие два это координаты места вставки изображения в “холст” GDI+, последний параметр это размер копируемой области.

gdi.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, bounds.Size);

Ну а теперь можно вывести полученное изображение в PictureBox на нашей форме:

img.BackgroundImageLayout = ImageLayout.Zoom;
img.BackgroundImage = captured;

Вся процедура обработки нажатия на кнопку btnCapture:

private void btnCapture_Click(object sender, EventArgs e)
{
     Rectangle bounds = Screen.PrimaryScreen.Bounds;
     int colourDepth = Screen.PrimaryScreen.BitsPerPixel;
     PixelFormat format;
     switch (colourDepth)
     {
          case 8:
          case 16:
              format = PixelFormat.Format16bppRgb565;
              break;
 
          case 24:
              format = PixelFormat.Format24bppRgb;
              break;
 
          case 32:
              format = PixelFormat.Format32bppArgb;
              break;
 
          default:
              format = PixelFormat.Format32bppArgb;
              break;
     }
     captured = new Bitmap(bounds.Width, bounds.Height, format);
     Graphics gdi = Graphics.FromImage(captured);
     gdi.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, bounds.Size);
     img.BackgroundImageLayout = ImageLayout.Zoom;
     img.BackgroundImage = captured;
}

Теперь создадим процедуры сохранения полученного изображения в файл. Сохранение в формате jpeg при нажатии на кнопке btnSaveJpg. Проверяем инициализирован ли объект bitmap, если да, то открываем диалоговое окно сохранения файла в котором настроен фильтр на отображение только изображений в формате jpeg, если файл выбран, то сохраняем, используя метод Save объекта Bitmap.

private void btnSaveJpg_Click(object sender, EventArgs e)
{
     if (captured != null)
     {
          dlg.Filter = "Jpeg image|*.jpg|All files|*.*";
          dlg.Title = "Save captured screen as jpeg";
          if (dlg.ShowDialog() == DialogResult.OK)
          {
               captured.Save(dlg.FileName, ImageFormat.Jpeg);
          }
     }
}

Сохранение в формате png при нажатии на кнопке btnSavePng.

private void btnSavePng_Click(object sender, EventArgs e)
{
     if (captured != null)
     {
          dlg.Filter = "PNG image|*.png|All files|*.*";
          dlg.Title = "Save captured screen as png";
          if (dlg.ShowDialog() == DialogResult.OK)
          {
              captured.Save(dlg.FileName, ImageFormat.Png);
          }
     }
}


3 Replies to “C# – Захват содержимого экрана (.net 2.0)”

  1. Спасибо за пример, я ещё добавил чтобы окно при снятии сворачивалось.

  2. Сергей, напишите статью, как сделать скриншот с приложений использующих directx(на c#).
    Поскольку этим методом, я так понимаю, сохранится, лишь черный экран.
    если можете, оповестите меня в случае написания данной статьи. dan-ver@ukr.net

  3. Наверно не
    captured = new Bitmap(bounds.Width, bounds.Height, format);
    а
    Bitmap captured = new Bitmap(bounds.Width, bounds.Height, format);

Leave a Reply

Понравилась статья? Поделить с друзьями:
  • System windows forms dll где находится
  • System windows forms datavisualization charting как подключить
  • System windows forms datavisualization charting chart
  • System windows forms datagridviewcell value get вернул null
  • System windows data error 40 bindingexpression path error