プログラミングとかブログ

Unity/C#/SRPGStudio/RPGツクールMVの情報とかその他気になったことを調べて書きます。

【C#】アクティブウィンドウのウィンドウ名を取得

user32.dllのGetForegroundWindow()とGetWindowText()を使います。

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

    [DllImport("user32.dll", EntryPoint = "GetWindowText", CharSet = CharSet.Auto)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder(65535);//65535に特に意味はない
        GetWindowText(GetForegroundWindow(), sb, 65535);
        Console.WriteLine(sb);
    }
}

・例
SRPGStudioを前面にします。
f:id:shirakamisauto:20160325165259p:plain
ウインドウタイトルが取得できました。
f:id:shirakamisauto:20160325165606p:plain