外部exe窗体嵌入winform

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Design;

namespace HCDL
{
    public class ShowForm
    {
        //-------------------
        //Action<object, EventArgs> appIdleAction = null;
        EventHandler appIdleEvent = null;

        Control ParentCon = null;

        string strGUID = "";

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

        /// <summary>
        /// 将属性<code>AppFilename</code>指向的应用程序打开并嵌入此容器
        /// </summary>
        public IntPtr Start(string FileNameStr)
        {
            if (m_AppProcess != null)
            {
                Stop();
            }
            try
            {
                ProcessStartInfo info = new ProcessStartInfo(FileNameStr);
                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;
            }
            if (m_AppProcess.MainWindowHandle == IntPtr.Zero) return;
            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
            {
                // Move the window to overlay it on this window
                MoveWindow(app.MainWindowHandle, -20, -20, control.Width, control.Height-10, 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;
    }
}

PS:以前是3.5版本。现在改成2.0也能用的了

用法

C# code?


1

2

ShowForm Sf = new ShowForm(this"仅供内部使用" + System.Guid.NewGuid().ToString());

            ProxHandle= Sf.Start(Application.StartupPath + "\\ProxyThorn.exe");

时间: 2024-07-31 16:05:38

外部exe窗体嵌入winform的相关文章

141107●Winform拖动无边框窗口、播放音频、启动外部exe程序

鼠标拖动无边框窗口 1. //鼠标拖动 Point downpoint = new Point(); //事件,鼠标按下,获取当前坐标 private void panel1_MouseDown(object sender, MouseEventArgs e) { downpoint.X = -e.X; downpoint.Y = -e.Y; } //事件,鼠标移动,赋值新坐标 private void panel1_MouseMove(object sender, MouseEventArgs

C# ASP.NET Webservice调用外部exe无效的解决方法

最近用asp.net做webservice,其中有个功能是调用执行外部的exe(类似cmd中执行),但执行Process.Start之后就没有结果,同样代码在winform下正常,折腾两天终于找到解决方法 本文参考了以下网页,十分感谢 http://bbs.csdn.net/topics/300053869 http://blog.163.com/[email protected]/blog/static/15737970200862331842368/ 环境:win7 sp1 64位 以及II

WPF中嵌入WinForm中的webbrowser控件

原文:WPF中嵌入WinForm中的webbrowser控件 使用VS2008创建WPF应用程序,需使用webbrowser.从工具箱中添加WPF组件中的webbrowser发现其中有很多属性事件不能使用.决定还是使用WinForm中的webbrowser.要想在WPF中使用WinForm控件,查看MSDN,需经过以下步骤. 创建名为 HostingWfInWpf 的 WPF 应用程序项目. 在解决方案资源管理器中,添加一个对名为 WindowsFormsIntegration.dll 的 Wi

windows下调用外部exe程序 SHELLEXECUTEINFO

本文主要介绍两种在windows下调用外部exe程序的方法: 1.使用SHELLEXECUTEINFO 和 ShellExecuteEx SHELLEXECUTEINFO 结构体的定义如下: 1 typedef struct _SHELLEXECUTEINFO { 2 DWORD cbSize; 3 ULONG fMask; 4 HWND hwnd; 5 LPCTSTR lpVerb; 6 LPCTSTR lpFile; 7 LPCTSTR lpParameters; 8 LPCTSTR lpD

C#和asp.net执行外部EXE程序

这两天研究下.Net的执行外部EXE程序问题,就是在一个程序里通过按钮或其他操作运行起来另外一个程序,需要传入参数,如用户名.密码之类(实际上很类似单点登录,不过要简单的多的多):总结如下: 1.CS版:WebForm的调用外部程序,很简单 (1)如果不考虑参数问题,仅仅是执行另外一个程序,用:System.Diagnostics.Process.Start("')即可: 如:System.Diagnostics.Process.Start("D:\\首字母拼音码.exe",

IE嵌入Winform不能显示问题

需要在客户端进行一些打印等需要操作客户端机器的功能,一种可以带带ActiveX的方法是直接嵌入Winform,很简洁,很方便,如下 https://social.msdn.microsoft.com/Forums/en-US/2c3bfca4-b616-48e5-9280-25db87981cbf/hosting-windows-forms-control-in-ie?forum=winforms 但是有时候不同的机器有的不能加载控件,很多原因, http://blog.jonschneider

c# 调用外部exe程序

c#调用外部exe程序,首先要 using System.Diagnostics; 然后开启一个新process System.Diagnostics.ProcessStartInfo p=null; System.Diagnostics.Process Proc; p = new ProcessStartInfo("nnnn.exe","参数"); p.WorkingDirectory = exepath;//设置此外部程序所在windows目录 p.Window

unity 读取外部exe程序控制台信息

由于需要获取显卡信息,但是unity的自带函数,只能输出1个显卡 c#倒是可以但是引用了一个下载的dll   System.Management.dll 这个dll放到unity用不了,因为mono不支持 所以先用vs写个外部exe程序 using System; using System.Management; public class Sample { public static void Main(string[] args) { string Gname = ""; Manag

winForm窗体嵌入U3d

最近新做一项目,需要winForm框架嵌入u3d,并且实现交互.从网上搜了各种资料,总结了三种方法: 1.直接打开exe程序 System.Diagnostics.Process.Start(@"D:\Demo\Demo1020.exe"); 缺点:u3d不嵌入到窗体 而是单独的打开. 优点:算是优点吧,画面还是比较流畅的 2.用网上封装好的方法嵌入窗体 可以看这里的实现 代码就不自己贴了 嫌麻烦 http://blog.csdn.net/lisenyang/article/detai