フルスクリーン検出

完全にメモなので後で修正
ほかウィンドウがフルスクリーン時は最前面をやめるってのを考える

ref:.d.hatena.ne.jp/ir9Ex/20060821/1156127138

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1 {


class Program {
[DllImport( "user32.dll" )]
static extern IntPtr GetForegroundWindow();

[DllImport( "user32.dll" )]
static extern int GetWindowRect( IntPtr hWnd, out RECT rect );

[DllImport( "user32.dll" )]
static extern bool IsWindowVisible( IntPtr hwnd );

[DllImport( "user32.dll" )]
static extern IntPtr GetWindow( IntPtr hwnd, int wCmd );

public const int GW_HWNDPREV = 3;

[StructLayout( LayoutKind.Sequential )]
public struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
}

public static void Main() {
// 検出状態
bool detected = false;
// 処理用一時変数
bool temp = false;
// メッセージ出力回数の記録
int i = 0;

Console.WriteLine( i + ":検出処理開始." );
do {
// フルスクリーンか確認して
temp = IsFullscreen();
// 最終の検出状態と状況が異なるなら
if ( detected != temp ) {
// 出力回数を増やして、最終の状態を更新して、ステータスを出力
i = i + 1;
detected = temp;
if ( detected ) {
Console.WriteLine( i + ":フルスクリーンアプリ検出." );
} else {
Console.WriteLine( i + ":フルスクリーンアプリ終了検出." );
}
}
// 検出のインターバルは長めのほうがよいとおもわれます
System.Threading.Thread.Sleep( 5000 );
} while ( true );
}

static public bool IsFullscreen() {
// ウィンドウサイズの比較用
RECT wRect = default( RECT );
Rectangle wndRect = default( Rectangle );
Rectangle scrRect = default( Rectangle );

// アクティブウィンドウのハンドル
var fore = GetForegroundWindow();
// 処理用一時変数
var temp = IntPtr.Zero;

// アクティブウィンドウのハンドルが取れなかったら失敗。
// とりあえずフルスクリーンではないとする。
if ( fore == IntPtr.Zero )
return false;

// アクティブウィンドウのサイズを取得。
// 失敗したらとりあえずフルスクリーンではないとする。
if ( !( GetWindowRect( fore, out wRect ) > 0 ) )
return false;
wndRect = new Rectangle( wRect.Left, wRect.Top, wRect.Right - wRect.Left, wRect.Bottom - wRect.Top );
scrRect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;

// スクリーンのサイズと同じでないか判定.
// 同じであるならフルスクリーン.WindowsXPのイメージプレビューのスライドショーとかはここで判明する.
if ( !wndRect.Equals( scrRect ) ) {
// アクティブウィンドウ以下のウィンドウについてループ
temp = GetWindow( fore, GW_HWNDPREV );
while ( !( temp == IntPtr.Zero ) ) {
// 1つでもウィンドウが可視状態なら、非フルスクリーンモード
if ( IsWindowVisible( temp ) ) {
return false;
}
temp = GetWindow( temp, GW_HWNDPREV );
}
}
return true;
}
}
}