1つのUnityアプリ(Standalone)で分離した複数Windowを使う

1つのアプリ内でデモ画面(フルスクリーン表示)と操作用画面(ウィンドウ表示)を表示したかったのでメモ

マルチディスプレイを設定する

以下のドキュメントに従ってマルチディスプレイの設定を行う。

ウィンドウ情報を変更する

マルチディスプレイを設定した場合、デフォルトでフルスクリーンモードで起動するのでウィンドウに関する情報を変更するクラスを作成してうウィンドウを任意の大きさに変更する。

public static class WindowController 
{
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    public static extern IntPtr FindWindow(System.String className, System.String windowName);

    // Sets window attributes
    [DllImport("user32.dll")]
    public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    // Gets window attributes
    [DllImport("user32.dll")]
    public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    // assorted constants needed
    public static int GWL_STYLE = -16;
    public static int WS_CHILD = 0x40000000; //child window
    public static int WS_BORDER = 0x00800000; //window with border
    public static int WS_DLGFRAME = 0x00400000; //window with double border but no title
    public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar

    public static void windowReplace(string name, int x, int y, int width, int height, bool hideTitleBar)
    {
        var window = FindWindow(null, name);

        if (hideTitleBar)
        {
            int style = GetWindowLong(window, GWL_STYLE);
            SetWindowLong(window, GWL_STYLE, (style & ~WS_CAPTION));
        }
        else
        {
            int style = GetWindowLong(window, GWL_STYLE);
            style |= WS_CAPTION;
            SetWindowLong(window, GWL_STYLE, style);
        }

        SetWindowPos(window, 0, x, y, width, height, width * height == 0 ? 1 : 0);
    }
}

この例の場合、タイトルバーありの移動できるウィンドウとタイトルバーなしの移動できないウィンドウを表示できる。

Display.displays[0].Activate();
Display.displays[1].Activate();

//本体の解像度設定(タイトルバーを隠さない)
WindowController.windowReplace("MultiWindow", 100, 100, 640, 480, false);

//Secondary Displayの解像度設定(タイトルバー隠す)
WindowController.windowReplace("Unity Secondary Display", 1000, 100, 640, 640, true);

フルHD(1920x1080)のモニターを2台横に並べた構成で片方のウィンドウをフルスクリーン表示にしたい場合は(x, y, width, height)=(1920,0,1920,1080)とする。

注意点

・PCに接続されているモニタ-より多い数のウィンドウが生成できない
・ウィンドウの最大数は8(Unityマルチウィンドウの上限)

この記事が気に入ったらサポートをしてみませんか?