LoginSignup
2
1

More than 5 years have passed since last update.

UnityからChromeブラウザの立ち上げと立ち下げ

Posted at

はじめに

UnityからChromeブラウザを立ち上げ、立ち上げたサイトだけを立ち下げたかったので、
備忘録として残しておきました。
(既にブラウザで開いていたサイトは表示したままにしておきたかった)
結構無理やりなので、汎用性はあまりないかもしれません。
はじめは「System.Diagnostics.Process」だけで実現しようとしましたが、
Chromeは起動させると別のプロセスIDに切り替えて起動してしまうような挙動をしていたため断念しました。

実行画面

  • わかりにくいですが、「W」キーを押してChromeを立ち下げています。 Chromeオンオフ

開発環境

  • Windows 10
  • Unity Ver 2018.3.2f1 Personal
  • Chrome バージョン: 72.0.3626.119  64bit

ポイント

  • Chromeをアプリモードで立ち上げる。(例としてGoogleサイトを表示)
  • 表示させたいサイトのサイト名は英語にする。(なぜか日本語だとhWndハンドルが取れなかった)

サンプルソースの説明(ChromeOnOff.cs)

  • Unityのゲーム再生時にStart関数内でChromeがアプリモードで起動
  • キーボードの「W」キーを押したとき、アプリモードで起動したChromeだけ立ち下がる。
ChromeOnOff.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class ChromeOnOff : MonoBehaviour
{
    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    static uint WM_CLOSE = 0x10;

    /// <summary>
    ///起動する外部プロセス
    /// </summary>
    private Process exProcess;

    // Use this for initialization
    void Start()
    {

        if (exProcess == null)
        {

            exProcess = new Process();

            exProcess.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";  // exe名
            exProcess.StartInfo.Arguments = "--app=https://www.google.com --incognito";                      // コマンド引数生成

            //外部のプロセスを実行
            exProcess.Start();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))    // Wキーを押した?(Yes)
        {
            WindowsCloseProc();             // ウインドウを閉じるWin32API
        }
    }

    // Chromeを閉じる処理
    private void WindowsCloseProc()
    {
        IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Google");    // サイト名を第二引数へ入力(日本語がダメっぽい)
        bool ret = CloseWindow(hWnd);
    }

    // WIN32APIにおけるSENDメッセージ
    static bool CloseWindow(IntPtr hWnd)
    {
        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        return true;
    }
}

おわりに

  • とりあえずWIN32APIを使うことで開いたページだけ落とすことができた。
  • 日本語のサイト名の場合に対応できないのが残念。(どなたかわかるかた教えてください。。。)
2
1
1

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
2
1