LoginSignup
11
9

More than 3 years have passed since last update.

Unityでデスクトップマスコットのためにタイトルバー非表示した

Last updated at Posted at 2018-02-27

はじめに

前回の記事に引き続き、Unityでデスクトップマスコットを作成しています。
その過程で必要なのがウィンドウのタイトルバーの非表示です。
こちらも前回同様、詰まった案件なのでメモ程度に記事に書こうと思います。

開発環境

  • Unity 5.6.3f1
  • Microsoft Visual Studio

前回と同じですね。

実際のコード

以下のようなコードを記述しました。

DisvisibleTitleBar.cs
using UnityEngine;
using System;
using System.Runtime.InteropServices;

public class DisvisibleTitleBar : MonoBehaviour
{

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

    [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
    private static extern uint GetWindowLong(int hWnd, int nIndex);
    [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
    private static extern uint SetWindowLong(int hWnd, int nIndex, uint dwNewLong);
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    private static extern int SetWindowPos(int hwnd, int hwndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

    int handle; // ウィンドウ

    const String WINDOW_NAME = "[ウィンドウの名前]"; // ウィンドウの名前

    const int GWL_STYLE = -16; // ウィンドウスタイルを書き換えるためのオフセット
    const int WS_BORDER = 0x00800000; // 境界線を持つウィンドウを作成
    const int WS_DLGFRAME = 0x00400000; // ダイアログボックスのスタイルの境界を持つウィンドウを作成
    const int WS_CAPTION = WS_BORDER | WS_DLGFRAME; // タイトルバーを持つウィンドウを作成

    const int HWND_TOP = 0x0; // 最前面に表示
    const uint SWP_NOSIZE = 0x1; // 現在のサイズを維持(cxとcyパラメータを無視)
    const uint SWP_NOMOVE = 0x2; // 現在の位置を維持(xとyパラメータを無視)
    const int SWP_FRAMECHANGED = 0x0020; // SetWindowLongの内容を適用
    const int SWP_SHOWWINDOW = 0x0040; // ウィンドウを表示

    void Start()
    {

#if UNITY_EDITOR

#else

        handle = FindWindow(null, WINDOW_NAME); // 指定したウィンドウを取得

        // タイトルバーを非表示
        uint style = GetWindowLong(handle, GWL_STYLE); // ウィンドウの情報を取得
        SetWindowLong(handle, GWL_STYLE, style ^ WS_CAPTION); // ウィンドウの属性を変更

        // SetWindowLongによる変更を適用
        SetWindowPos(handle, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED | SWP_SHOWWINDOW);

#endif

    }

}

今回もUnity Editorで実行するとめんどくさいことになるので
ビルドしたプログラムでのみ非表示になるようにしています。
また、今回はあらかじめタイトルバーを非表示にするウィンドウを
ウィンドウの名前から指定できるようにしました。

しかし、タイトルバーを消すとウィンドウ右上にある閉じるボタンも
非表示になってしまうため、タスクマネージャーとかで終了させる必要があります。

(2020年2月25日追記)
上記の方法でも少しタイトルバーが残ってしまうことがあるようです。
こちらにその対処法が紹介されていましたので参考にして下さい。
https://teratail.com/questions/190646

最後に

今回の記事と前回の記事を使えば
デスクトップマスコットに近づくかと思います。
今後はウィンドウの移動でマスコットの移動を表現したり、
マスコットにいろいろなリアクションを実装したいですね。

参考

http://dss.o.oo7.jp/cgi/PT.cgi?VCPP/MFC/Window/WindowTitleBar
https://gist.github.com/mattatz/ca84b487c5697e7d43f8216c57a2b975
http://chokuto.ifdef.jp/urawaza/prm/window_style.html

11
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9