ディスプレイの解像度が変化したことを取得する

注意:
この文書は以前「.NETでいきまっしょい!」で公開していたものですが、公開以降メンテナンスされていません。 今や古い情報となった内容が記載されている場合があるのでご注意ください。

Microsoft.Win32.SystemEventsクラスのDisplaySettingsChangedイベントはディスプレイに関する設定が変化したときに発生するイベント。 このイベントを用いることで、ディスプレイ解像度が変化したことを取得する。 この例ではディスプレイサイズを取得するのにScreen.GetBounds()を用いているが、これはScreen.PrimaryScreen.Boundsでは変更後に正しくサイズを取得できなかったため。 なお、このコードはマルチディスプレイ環境での実行は想定していない。

VB.NET
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports Microsoft.Win32

Class MainForm

    Inherits Form

    ' 現在のスクリーンの範囲を保持しておくための変数
    Private currentScreenBound As Rectangle

    Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' 現在のスクリーンの範囲を取得
        currentScreenBound = Screen.GetBounds(New Point(0, 0))

        ' ディスプレイに関する設定が変更されたことを知るためのイベントハンドラを割り当てる
        AddHandler SystemEvents.DisplaySettingsChanged, AddressOf SystemEvents_DisplaySettingChanged

    End Sub

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

        ' 新しいスクリーンの範囲を取得
        Dim newScreenBound As Rectangle = Screen.GetBounds(New Point(0, 0))

        ' 以前の範囲と比較
        If Not currentScreenBound.Equals(newScreenBound) Then

            System.Diagnostics.Trace.WriteLine(String.Format("ディスプレイサイズが{0}から{1}に変更されました。", currentScreenBound, newScreenBound))

            currentScreenBound = newScreenBound

        End If

    End Sub

End Class
C#
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;

class MainForm : Form
{
    // 現在のスクリーンの範囲を保持しておくための変数
    private Rectangle currentScreenBound;

    private MainForm()
    {
        this.Load += new EventHandler( Form_Load );
        
        // ディスプレイに関する設定が変更されたことを知るためのイベントハンドラを割り当てる
        SystemEvents.DisplaySettingsChanged += new EventHandler( SystemEvents_DisplaySettingChanged );
    }

    private void Form_Load( object sender, EventArgs e )
    {
        // 現在のスクリーンの範囲を取得
        currentScreenBound = Screen.GetBounds( new Point( 0, 0 ) );
    }

    private void SystemEvents_DisplaySettingChanged( object sender, EventArgs e )
    {
        // 新しいスクリーンの範囲を取得
        Rectangle newScreenBound = Screen.GetBounds( new Point( 0, 0 ) );

        // 以前の範囲と比較
        if ( !currentScreenBound.Equals( newScreenBound ) )
        {
            System.Diagnostics.Trace.WriteLine( String.Format( "ディスプレイサイズが{0}から{1}に変更されました。", currentScreenBound, newScreenBound ) );

            currentScreenBound = newScreenBound;
        }
    }
}