Winform嵌入其它應用程式

来源:http://www.cnblogs.com/s0611163/archive/2017/10/23/7716075.html
-Advertisement-
Play Games

Options: using CommandLine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namesp ...


Options:

using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SunCreate.CombatPlatform.Client
{
    public class Options
    {
        [Option("h", "handle", Required = true)]
        public int Handle { get; set; }

        [Option("b", "browser")]
        public Boolean IsBrowser { get; set; }
    }

}
View Code

ApplicationHost:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace SunCreate.CombatPlatform.Client
{
    /// <summary>
    /// 
    /// </summary>
    public class ApplicationHost : UserControl
    {
        #region PInvoke
        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [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 = "SetWindowLongA", SetLastError = true)]
        private static extern long SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);
        #endregion


        #region Const
        private const int GWL_STYLE = -16;
        private const int WS_VISIBLE = 0x10000000;
        #endregion


        #region Var
        private Boolean _autoLoadProcess = true;
        private Process _process;
        private string _file;
        private string _arguments;
        #endregion


        #region Private Property
        /// <summary>
        /// Gets or sets the m_ process.
        /// </summary>
        /// <value>
        /// The m_ process.
        /// </value>
        private Process m_Process
        {
            get
            {
                return _process;
            }
            set
            {
                if (_process == value)
                    return;

                if (value == null)
                    UnloadProcess();

                _process = value;
            }
        }
        #endregion


        #region Public Property
        /// <summary>
        /// Gets or sets the auto load process.
        /// </summary>
        /// <value>
        /// The auto load process.
        /// </value>
        public Boolean AutoLoadProcess
        {
            get
            {
                return _autoLoadProcess;
            }
            set
            {
                _autoLoadProcess = value;
            }
        }

        /// <summary>
        /// Gets or sets the hide application title bar.
        /// </summary>
        /// <value>
        /// The hide application title bar.
        /// </value>
        public Boolean HideApplicationTitleBar { get; set; }

        /// <summary>
        /// Gets or sets the file.
        /// </summary>
        /// <value>
        /// The file.
        /// </value>
        public string File
        {
            get
            {
                return _file ?? string.Empty;
            }
            set
            {
                _file = value;
            }
        }

        /// <summary>
        /// Gets or sets the arguments.
        /// </summary>
        /// <value>
        /// The arguments.
        /// </value>
        public string Arguments
        {
            get
            {
                return _arguments ?? string.Empty;
            }
            set
            {
                _arguments = value;
            }
        }

        /// <summary>
        /// Gets the main window handle.
        /// </summary>
        /// <value>
        /// The main window handle.
        /// </value>
        public IntPtr MainWindowHandle 
        {
            get
            {
                return m_Process == null ? IntPtr.Zero : m_Process.MainWindowHandle;
            }
        }

        /// <summary>
        /// Gets the main window title.
        /// </summary>
        /// <value>
        /// The main window title.
        /// </value>
        public string MainWindowTitle
        {
            get
            {
                return m_Process == null ? string.Empty : m_Process.MainWindowTitle;
            }
        }
        #endregion


        #region Constructor & DeConstructor
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
        /// </summary>
        public ApplicationHost()
        {
            this.Load += ApplicationHost_Load;
            this.ProcessLoaded += ApplicationHost_ProcessLoaded;
            this.ProcessUnLoaded += ApplicationHost_ProcessUnLoaded;
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="ApplicationHost" /> class.
        /// </summary>
        ~ApplicationHost()
        {
            m_Process = null;
        }
        #endregion


        #region Event
        public event EventHandler ProcessLoaded;
        public event EventHandler ProcessUnLoaded;
        #endregion


        #region Protected Method
        /// <summary>
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                m_Process = null;
            }
            base.Dispose(disposing);
        }

        /// <summary>
        /// Raises the <see cref="E:ProcessLoaded" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void OnProcessLoaded(EventArgs e)
        {
            if (ProcessLoaded == null)
                return;
            ProcessLoaded(this, e);
        }

        /// <summary>
        /// Raises the <see cref="E:ProcessUnLoaded" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void OnProcessUnLoaded(EventArgs e)
        {
            if (ProcessUnLoaded == null)
                return;
            ProcessUnLoaded(this, e);
        }
        #endregion


        #region Public Method
        /// <summary>
        /// Loads the process.
        /// </summary>
        public void LoadProcess()
        {
            if (m_Process != null)
            {
                var startInfo = m_Process.StartInfo;
                if (startInfo.FileName != this.File || startInfo.Arguments != this.Arguments)
                    m_Process = null;
                else
                    return;
            }

            m_Process = new Process()
            {
                SynchronizingObject = this,
                StartInfo = new ProcessStartInfo()
                {
                    FileName = File,
                    Arguments = this.Arguments
                }
            };
        
            m_Process.Start();

            m_Process.WaitForInputIdle();
            while (!m_Process.HasExited && m_Process.MainWindowHandle == IntPtr.Zero)
            {
                Application.DoEvents();
                Thread.Sleep(100);
            }

            m_Process.EnableRaisingEvents = true;

            m_Process.Exited += m_Process_Exited;

            var handle = m_Process.MainWindowHandle;

            if (HideApplicationTitleBar)
                SetWindowLong(handle, GWL_STYLE, WS_VISIBLE);

            SetParent(handle, this.Handle);

            MoveWindow(handle, 0, 0, this.Width, this.Height, true);

            OnProcessLoaded(EventArgs.Empty);
        }

        /// <summary>
        /// Unloads the process.
        /// </summary>
        public void UnloadProcess()
        {
            if (m_Process == null)
                return;

            if (m_Process.HasExited)
                return;

            m_Process.CloseMainWindow();
            m_Process.WaitForExit(100);

            if (m_Process != null && !m_Process.HasExited)
                m_Process.Kill();

            OnProcessUnLoaded(EventArgs.Empty);
        }

        /// <summary>
        /// Reloads the process.
        /// </summary>
        public void ReloadProcess()
        {
            UnloadProcess();
            LoadProcess();
        }
        #endregion


        #region Event Process
        /// <summary>
        /// Handles the Load event of the ApplicationHost control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        void ApplicationHost_Load(object sender, EventArgs e)
        {
            if (Process.GetCurrentProcess().ProcessName.Equals("devenv", StringComparison.CurrentCultureIgnoreCase))
                return;

            if (AutoLoadProcess)
                LoadProcess();
        }

        /// <summary>
        /// Handles the Resize event of the ApplicationHost control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        void ApplicationHost_Resize(object sender, EventArgs e)
        {
            var handle = m_Process.MainWindowHandle;

            if (handle != IntPtr.Zero)
                MoveWindow(handle, 0, 0, this.Width, this.Height, true);
        }

        /// <summary>
        /// Handles the ProcessLoaded event of the ApplicationHost control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        void ApplicationHost_ProcessLoaded(object sender, EventArgs e)
        {
            this.Resize += ApplicationHost_Resize;
        }

        /// <summary>
        /// Handles the ProcessUnLoaded event of the ApplicationHost control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        void ApplicationHost_ProcessUnLoaded(object sender, EventArgs e)
        {
            this.Resize -= ApplicationHost_Resize;
        }

        /// <summary>
        /// Handles the Exited event of the m_Process control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        void m_Process_Exited(object sender, EventArgs e)
        {
            m_Process = null;

            OnProcessUnLoaded(EventArgs.Empty);
        }
        #endregion
    }
}
View Code

代碼:

private void ShowBrowser(string url)
{
    if (dkPnl.Children.Count > 0)
    {
        WindowsFormsHost whst = dkPnl.Children[0] as WindowsFormsHost;
        whst.Dispose();
        foreach (Process p in Process.GetProcessesByName("MyBrowser"))
        {
            p.Kill();
        }
    }

    var host = new ApplicationHost()
    {
        File = @"MyBrowser.exe",
        Arguments = string.Empty,
        HideApplicationTitleBar = true,
        Dock = System.Windows.Forms.DockStyle.Fill,
        BorderStyle = System.Windows.Forms.BorderStyle.None
    };
    host.ProcessLoaded += host_ProcessLoaded;
    host.ProcessUnLoaded += host_ProcessUnLoaded;

    WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
    windowsFormsHost.Child = host;
    dkPnl.Children.Add(windowsFormsHost);
}

private Dictionary<IntPtr, ApplicationHost> _hostPool;
private Dictionary<IntPtr, ApplicationHost> m_HostPool
{
    get
    {
        return _hostPool ?? (_hostPool = new Dictionary<IntPtr, ApplicationHost>());
    }
}

void host_ProcessLoaded(object sender, EventArgs e)
{
    var host = sender as ApplicationHost;
    m_HostPool.Add(host.MainWindowHandle, host);
}

void host_ProcessUnLoaded(object sender, EventArgs e)
{
    var host = sender as ApplicationHost;

    var parent = host.Parent;
    if (parent != null && !parent.IsDisposed)
    {
        parent.Dispose();
    }
}
View Code

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天遇到這麼一個問題,打開VS啟動調試,始終報錯,如下圖: 我重啟VS,甚至重啟電腦都不得行,那個進程號還在變化,就在網上查找資料,各式各樣的解決方案,這裡我記錄我成功的方案。 打開項目文件地址,在解決方案根目錄下找到.vs文件: 刪除.vs 然後重啟vs即可。 ...
  • 手繪視頻最終的生成物是視頻文件,前面幾篇主要講的是手繪視頻的創作部分,今天講一下手繪視頻的導出問題。主要以 UWP 為例,另外會介紹一些 Web 端遇到的問題和解決方法。 如上所述,手繪視頻在創作後,最終會導出為視頻文件,如 MP4,WMV 等,我們目前的選擇是 MP4,整個導出大致分為幾個步驟: ...
  • Html.DropDownList傳值: 可以傳入明確的IEnumerable<SelectListItem>,也可以通過ViewBag或者ViewData隱式地傳入,前提是需要相同的名稱,比如:ViewBag.GenreId或者ViewData["GenreId"]。 示例: 視圖: 註意: 1. ...
  • C#的編譯器總是將匿名類型編譯成internal的,當在視圖中直接使用控制器傳遞的匿名對象時就會報錯錯誤代碼:控制器代碼視圖代碼執行結果:********************************************************************************* ...
  • 此示例展示了框架級依賴註入如何在 ASP.NET Core 中工作。 其簡單但功能強大,足以完成大部分的依賴註入工作。 ...
  • 直接代碼 樣式代碼 調用實例 效果展示 本文原創出處:http://www.cnblogs.com/PettyHandSome/ 歡迎各位轉載,但是未經作者本人同意,轉載文章之後必須在文章頁面明顯位置給出作者和原文連接,否則保留追究法律責任的權利! ...
  • 1.起因 同事在調用錄音控制項生成的MP3,在部分瀏覽器中載入失敗,出現彈框提示。 經過同事的對比,發現當文件屬性中比特率 為0kbps,時長為空的時候就會出現上圖這種情況。並給找到一個解決方案,使用ffmpeg進行一次轉碼後就會出現比特率和時長,瀏覽器也可以正常載入。 異常的情況 正常的情況 2.問 ...
  • 1、實現ILifeSpanHandler介面,為了支持帶type="POST" target="_blank"的鏈接,並且為了後面能夠獲取到ChromiumWebBrowser並釋放舊的ChromiumWebBrowser,新窗體還是要讓它彈的,只不過後面會隱藏它,代碼如下: using CefSh ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...