CSMemo041

BACK

よそのウィンドウを取り込む

ウィンドウのタイトル名を入力してボタンを押すと、自フォームの中にそのウィンドウを取り込みます。

…何に使えるのやら…(笑)

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowCatcher
{
    public partial class Form1 : Form
    {
        private List<IntPtr> windows;

        public Form1()
        {
            InitializeComponent();
            this.SetBounds(0, 0, 640, 480, BoundsSpecified.Size);
            windows = new List<IntPtr>();
        }

        private void btnCatch_Click(object sender, EventArgs e)
        {
            IntPtr hwnd = FindWindow(null, cmbWindowTitle.Text);
            if (hwnd != null && !windows.Contains(hwnd))
            {
                MoveWindow(hwnd, 0, 0, 320, 240, true);
                SetParent(hwnd, this.Handle);
                windows.Add(hwnd);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 解放
            foreach (IntPtr hwnd in windows)
            {
                SetParent(hwnd, (IntPtr)null);
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr FindWindow(
            string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern int MoveWindow(
            IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr SetParent(
              IntPtr hWndChild, IntPtr hWndNewParent);
    }
}

追伸

Win32APIにはGetDesktopWindowというデスクトップの実体のハンドルを取得するやつもあるので、それを使って得たウィンドウを取り込んだらどうなるのかなー、わくわく♪…って試してみましたが、何も起こりませんでした。ハンドルはちゃんと取得できてるみたいなんだけどねー。ちゅまんなーい。

最終更新:2015年12月02日 00:04
添付ファイル