コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】コンソールアプリケーションでタスクバーのアイコンを点滅させてみる

ソースコード

using System;
using System.Runtime.InteropServices;
using System.Text;

public static class Program
{
    private delegate bool EnumWindowsDelegate( IntPtr hWnd, IntPtr lparam );

    [DllImport( "user32.dll" )]
    static extern Int32 FlashWindowEx( ref FLASHWINFO pwfi );

    [DllImport( "user32.dll" )]
    [return: MarshalAs( UnmanagedType.Bool )]
    private extern static bool EnumWindows( EnumWindowsDelegate lpEnumFunc, IntPtr lparam );

    [DllImport( "user32.dll", CharSet = CharSet.Auto, SetLastError = true )]
    private static extern int GetClassName( IntPtr hWnd, StringBuilder lpClassName, int nMaxCount );

    [StructLayout( LayoutKind.Sequential )]
    public struct FLASHWINFO
    {
        public UInt32 cbSize   ; // FLASHWINFO構造体のサイズ
        public IntPtr hwnd     ; // 点滅対象のウィンドウ・ハンドル
        public UInt32 dwFlags  ; // 以下の「FLASHW_XXX」のいずれか
        public UInt32 uCount   ; // 点滅する回数
        public UInt32 dwTimeout; // 点滅する間隔(ミリ秒単位)
    }

    public const UInt32 FLASHW_STOP      = 0 ; // 点滅を止める
    public const UInt32 FLASHW_CAPTION   = 1 ; // タイトルバーを点滅させる
    public const UInt32 FLASHW_TRAY      = 2 ; // タスクバー・ボタンを点滅させる
    public const UInt32 FLASHW_ALL       = 3 ; // タスクバー・ボタンとタイトルバーを点滅させる
    public const UInt32 FLASHW_TIMER     = 4 ; // FLASHW_STOPが指定されるまでずっと点滅させる
    public const UInt32 FLASHW_TIMERNOFG = 12; // ウィンドウが最前面に来るまでずっと点滅させる

    private static string m_searchClassName;
    private static IntPtr m_hWnd;

    private static void Main()
    {
        m_searchClassName = "Unity";
        EnumWindows( new EnumWindowsDelegate( EnumWindowCallBack ), IntPtr.Zero );

        var fInfo = new FLASHWINFO();
        fInfo.cbSize    = Convert.ToUInt32( Marshal.SizeOf( fInfo ) );
        fInfo.hwnd      = m_hWnd;
        fInfo.dwFlags   = FLASHW_TRAY;
        fInfo.uCount    = 0;
        fInfo.dwTimeout = 0;

        FlashWindowEx( ref fInfo );
    }

    private static bool EnumWindowCallBack( IntPtr hWnd, IntPtr lparam )
    {
        var csb = new StringBuilder( 256 );
        GetClassName( hWnd, csb, csb.Capacity );
        if ( !csb.ToString().Contains( m_searchClassName ) ) return true;
        m_hWnd = hWnd;
        return true;
    }
}

参考サイト様