启动第三方程序并嵌入到指定容器中

通过调用API 方法实现嵌入第三方程序窗口到指定容器

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace winformEmbedingExample
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
        [DllImport("user32.dll", EntryPoint = "GetWindowLong")]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        private const int GWL_STYLE = -16;
        private const int WS_CAPTION = 0xC00000;
        private Process process;
        private const int WS_CHILD = 0x40000000;
        private const int WS_VISIBLE = 0x10000000;



        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
            Closing += Form1_Closing;

        }

        private void Form1_Closing(object sender, CancelEventArgs e)
        {
           
            Process[] ps = Process.GetProcessesByName("Project2");
            foreach (var p in ps) {
                p.Kill();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void StartThirdPartApplication()
        {
            process = Process.Start("Project2.exe");
            process.WaitForInputIdle();
            IntPtr pWnd = process.MainWindowHandle;
            int style = GetWindowLong(pWnd, GWL_STYLE);
            style &= ~WS_CAPTION;
            style |= WS_CHILD;
            SetWindowLong(pWnd, GWL_STYLE, style);
            SetParent(pWnd, panel1.Handle);
            MoveWindow(pWnd, 0, 0, panel1.Width, panel1.Height, false);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            StartThirdPartApplication();
        }
    }
}

效果

image

posted @   丹心石  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示