求教:winform窗体嵌入第三方程序的窗体

我和我的代码互怼 2020-11-26 03:20:15
各位大佬下午好,如题所示,我在摆弄的时候的确可以做到一些窗体嵌入到我的winform里面,如以下代码:
在winform里面添加一个按钮和panel控件,代码如下:

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

namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
[DllImport("User32.dll ", EntryPoint = "SetParent")]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll ", EntryPoint = "ShowWindow")]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);


public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
p.Start();
System.Threading.Thread.Sleep(500);
SetParent(p.MainWindowHandle, panel1.Handle);
ShowWindow(p.MainWindowHandle, 3);
}

}
}



单击按钮后的确可以进行显示与操作,但是我遇到以下问题,并希望按照我说希望的运行:
1、打开的cmd首先在系统桌面上显示,之后才被装到我的winform里面,可以把System.Threading.Thread.Sleep(500)这里的500改成2000,这样会看得更清楚。我希望是指定的程序本来就在我的winform里面,而不是先在系统运行再装到winform里面;
2、执行的程序如果改成视频路径,那么画面简直要卡死,搞不清楚问题,这里是缺什么声明吗,还是哪里不对呢?
3、如果我在winform里面的cmd里面执行一个程序,这个程序就会在系统桌面弹出来,而不是在我的winform里面,求解怎么弄
...全文
3341 点赞 收藏 3
写回复
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
datafansbj 2020-11-27
1、你需要在嵌入前,设置第三方窗体的位置,恰好在你需要嵌入的位置,这样三方窗体出现的时候就已嵌入好了,不会出现闪烁
2、没看懂,“程序改成视频路径”是什么骚操作?具体一点吧
3、你的 WinForm 程序里执行 cmd,是怎么个执行法儿?是调用系统的 cmd 吗?还是自己写了一个类 cmd 的模块?如果是系统的 cmd ,当然会出现在桌面,因为系统的 cmd 窗口是另一个窗口,除非你将系统的 cmd 窗口再次做嵌入操作

希望楼主把问题描述清晰一些,这样有助于快速解决问题。
回复
我之前用过的,你可以试一试

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TrailSystem.BLL
{
    public class exeToForm
    {
        EventHandler appIdleEvent = null;
        Control ParentCon = null;
        string strGUID = "";
        string appName = "";

        public exeToForm(Control C, string Titlestr)
        {
            appIdleEvent = new EventHandler(Application_Idle);
            ParentCon = C;
            strGUID = Titlestr;
        }

        /// <summary>
        /// 将属性<code>AppFilename</code>指向的应用程序打开并嵌入此容器
        /// </summary>
        public IntPtr Start(string FilePath, string FileNameStr)
        {
            if (m_AppProcess != null)
            {
                Stop();
            }
            try
            {
                ProcessStartInfo info = new ProcessStartInfo(FileNameStr);
                info.WorkingDirectory = FilePath;
                info.UseShellExecute = true;
                info.WindowStyle = ProcessWindowStyle.Minimized;
                m_AppProcess = System.Diagnostics.Process.Start(info);
                m_AppProcess.WaitForInputIdle();
                Application.Idle += appIdleEvent;
            }
            catch
            {
                if (m_AppProcess != null)
                {
                    if (!m_AppProcess.HasExited)
                        m_AppProcess.Kill();
                    m_AppProcess = null;
                }
            }
            return m_AppProcess.Handle;
        }
        /// <summary>
        /// 确保应用程序嵌入此容器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Application_Idle(object sender, EventArgs e)
        {
            if (this.m_AppProcess == null || this.m_AppProcess.HasExited)
            {
                this.m_AppProcess = null;
                Application.Idle -= appIdleEvent;
                return;
            }

            while (m_AppProcess.MainWindowHandle == IntPtr.Zero)
            {
                Thread.Sleep(100);
                m_AppProcess.Refresh();
            }
            Application.Idle -= appIdleEvent;
            EmbedProcess(m_AppProcess, ParentCon);
        }
        /// <summary>
        /// 应用程序结束运行时要清除这里的标识
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void m_AppProcess_Exited(object sender, EventArgs e)
        {
            m_AppProcess = null;
        }
        /// <summary>
        /// 将属性<code>AppFilename</code>指向的应用程序关闭
        /// </summary>
        public void Stop()
        {
            if (m_AppProcess != null)// && m_AppProcess.MainWindowHandle != IntPtr.Zero)
            {
                try
                {
                    if (!m_AppProcess.HasExited)
                        m_AppProcess.Kill();
                }
                catch (Exception)
                {
                }
                m_AppProcess = null;
            }
        }


        #region 属性
        /// <summary>
        /// application process
        /// </summary>
        Process m_AppProcess = null;

        /// <summary>
        /// 标识内嵌程序是否已经启动
        /// </summary>
        public bool IsStarted { get { return (this.m_AppProcess != null); } }

        #endregion 属性

        #region Win32 API
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
             CharSet = CharSet.Unicode, ExactSpelling = true,
             CallingConvention = CallingConvention.StdCall)]
        private static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);

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

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

        [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
        private static extern long GetWindowLong(IntPtr hwnd, int nIndex);

        public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong)
        {
            if (IntPtr.Size == 4)
            {
                return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
            }
            return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
        }
        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, int dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        private static extern bool PostMessage(IntPtr hwnd, uint Msg, uint wParam, uint lParam);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetParent(IntPtr hwnd);

        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private const int SWP_NOOWNERZORDER = 0x200;
        private const int SWP_NOREDRAW = 0x8;
        private const int SWP_NOZORDER = 0x4;
        private const int SWP_SHOWWINDOW = 0x0040;
        private const int WS_EX_MDICHILD = 0x40;
        private const int SWP_FRAMECHANGED = 0x20;
        private const int SWP_NOACTIVATE = 0x10;
        private const int SWP_ASYNCWINDOWPOS = 0x4000;
        private const int SWP_NOMOVE = 0x2;
        private const int SWP_NOSIZE = 0x1;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 0x10000000;
        private const int WM_CLOSE = 0x10;
        private const int WS_CHILD = 0x40000000;

        private const int SW_HIDE = 0; //{隐藏, 并且任务栏也没有最小化图标}
        private const int SW_SHOWNORMAL = 1; //{用最近的大小和位置显示, 激活}
        private const int SW_NORMAL = 1; //{同 SW_SHOWNORMAL}
        private const int SW_SHOWMINIMIZED = 2; //{最小化, 激活}
        private const int SW_SHOWMAXIMIZED = 3; //{最大化, 激活}
        private const int SW_MAXIMIZE = 3; //{同 SW_SHOWMAXIMIZED}
        private const int SW_SHOWNOACTIVATE = 4; //{用最近的大小和位置显示, 不激活}
        private const int SW_SHOW = 5; //{同 SW_SHOWNORMAL}
        private const int SW_MINIMIZE = 6; //{最小化, 不激活}
        private const int SW_SHOWMINNOACTIVE = 7; //{同 SW_MINIMIZE}
        private const int SW_SHOWNA = 8; //{同 SW_SHOWNOACTIVATE}
        private const int SW_RESTORE = 9; //{同 SW_SHOWNORMAL}
        private const int SW_SHOWDEFAULT = 10; //{同 SW_SHOWNORMAL}
        private const int SW_MAX = 10; //{同 SW_SHOWNORMAL}

        #endregion Win32 API

        /// <summary>
        /// 将指定的程序嵌入指定的控件
        /// </summary>
        private void EmbedProcess(Process app, Control control)
        {
            // Get the main handle
            if (app == null || app.MainWindowHandle == IntPtr.Zero || control == null) return;

            try
            {
                // Put it into this form
                SetParent(app.MainWindowHandle, control.Handle);
            }
            catch (Exception)
            { }
            try
            {
                // Remove border and whatnot               
                SetWindowLong(new HandleRef(this, app.MainWindowHandle), GWL_STYLE, WS_VISIBLE);
                SendMessage(app.MainWindowHandle, WM_SETTEXT, IntPtr.Zero, strGUID);
            }
            catch (Exception)
            { }
            try
            {
                // 移动窗口以将其覆盖在此窗口上
                MoveWindow(app.MainWindowHandle, 0, -20, control.Width, control.Height + 20, true);
            }
            catch (Exception)
            { }
        }

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        const int WM_SETTEXT = 0x000C;
    }
}

窗体内使用:

exeToForm fr = new exeToForm(panel1, "");
fr.Start(Application.StartupPath + "\\应用目录", Application.StartupPath + "\\应用目录\\应用名");
回复
韩老骥 2020-11-26
你要不试试勾子,拦截WM_CREATE消息。窗体创建未显示的时候,立即获取窗体句柄。
回复
相关推荐
发帖
C#
创建于2007-09-28

10.6w+

社区成员

.NET技术 C#
申请成为版主
帖子事件
创建了帖子
2020-11-26 03:20
社区公告

让您成为最强悍的C#开发者