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