91网首页-91网页版-91网在线观看-91网站免费观看-91网站永久视频-91网站在线播放

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

在C# WinForms中嵌入和控制外部程序的完整指南

admin
2025年5月25日 21:4 本文熱度 267

在開發Windows桌面應用程序時,我們經常需要在自己的應用程序中嵌入并控制其他可執行程序。本文將詳細介紹如何在C# WinForms應用程序中實現這一功能,并提供多個實用示例。

基本概念

嵌入外部程序意味著將其他Windows應用程序的窗口作為子窗口嵌入到我們的WinForms應用程序中。這種技術通常用于:

  • 集成第三方工具
  • 創建復合應用程序
  • 提供統一的用戶界面
  • 控制和管理多個應用程序

技術實現

基本實現類

創建一個專門用于管理嵌入程序的類:

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

namespace AppEmbedding
{
    publicclass ExternalProcessManager
    {

        // Windows API 常量  
        privateconstint GWL_STYLE = -16;
        privateconstint WS_CHILD = 0x40000000;
        privateconstint WS_VISIBLE = 0x10000000;

        // Windows API 聲明  
        privatestaticclass WindowsAPI
        {

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

            [DllImport("user32.dll")]
            public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

            [DllImport("user32.dll")]
            public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

            [DllImport("user32.dll")]
            public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

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

        private Process _embeddedProcess;
        private Control _parentControl;

        public ExternalProcessManager(Control parentControl)
        
{
            _parentControl = parentControl;
        }

        public void EmbedProcess(string processPath)
        
{
            try
            {
                // 啟動進程 - 使用 UseShellExecute = false 可能對某些應用程序更有效  
                ProcessStartInfo startInfo = new ProcessStartInfo(processPath)
                {
                    UseShellExecute = false,
                    CreateNoWindow = false
                };

                _embeddedProcess = Process.Start(startInfo);

                // 使用超時機制等待窗口句柄創建,避免無限等待  
                _embeddedProcess.WaitForInputIdle(3000);

                // 設置等待主窗口句柄的超時時間  
                DateTime timeout = DateTime.Now.AddSeconds(5);
                while (_embeddedProcess.MainWindowHandle == IntPtr.Zero)
                {
                    if (DateTime.Now > timeout)
                    {
                        thrownew TimeoutException("無法獲取進程主窗口句柄");
                    }
                    Application.DoEvents(); // 保持UI響應  
                    System.Threading.Thread.Sleep(100);
                }

                // 設置父窗口  
                WindowsAPI.SetParent(_embeddedProcess.MainWindowHandle, _parentControl.Handle);

                // 設置窗口樣式  
                int style = WindowsAPI.GetWindowLong(_embeddedProcess.MainWindowHandle, GWL_STYLE);
                style |= WS_CHILD | WS_VISIBLE; // 添加WS_VISIBLE確保窗口可見  
                WindowsAPI.SetWindowLong(_embeddedProcess.MainWindowHandle, GWL_STYLE, style);

                // 調整窗口位置和大小  
                WindowsAPI.MoveWindow(
                    _embeddedProcess.MainWindowHandle,
                    00,
                    _parentControl.ClientSize.Width,
                    _parentControl.ClientSize.Height,
                    true
                );

                // 確保父控件在尺寸變化時調整嵌入程序的大小  
                _parentControl.SizeChanged += (sender, e) =>
                {
                    if (_embeddedProcess != null && !_embeddedProcess.HasExited)
                    {
                        WindowsAPI.MoveWindow(
                            _embeddedProcess.MainWindowHandle,
                            00,
                            _parentControl.ClientSize.Width,
                            _parentControl.ClientSize.Height,
                            true
                        );
                    }
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show($"嵌入進程時出錯: {ex.Message}""錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void CloseEmbeddedProcess()
        
{
            if (_embeddedProcess != null && !_embeddedProcess.HasExited)
            {
                try
                {
                    _embeddedProcess.CloseMainWindow();
                    if (!_embeddedProcess.WaitForExit(3000))
                    {
                        _embeddedProcess.Kill();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"關閉進程時出錯: {ex.Message}""錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    _embeddedProcess.Dispose();
                    _embeddedProcess = null;
                }
            }
        }
    }
}

實際應用示例

嵌入記事本示例

public partial class NotePadForm : Form
{
    private ExternalProcessManager _processManager;

    public NotePadForm()
    
{
        InitializeComponent();

        // 創建一個Panel用于容納記事本
        Panel notepadPanel = new Panel
        {
            Dock = DockStyle.Fill
        };
        this.Controls.Add(notepadPanel);

        _processManager = new ExternalProcessManager(notepadPanel);
    }

    private void btnEmbedNotepad_Click(object sender, EventArgs e)
    
{
        _processManager.EmbedProcess("notepad.exe");
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    
{
        _processManager.CloseEmbeddedProcess();
        base.OnFormClosing(e);
    }
}

嵌入計算器示例

public partial class CalculatorForm : Form
{
    private ExternalProcessManager _processManager;
    private Panel _calcPanel;

    public CalculatorForm()
    
{
        InitializeComponent();

        // 創建計算器面板
        _calcPanel = new Panel
        {
            Size = new Size(300400),
            Location = new Point(1010)
        };
        this.Controls.Add(_calcPanel);

        _processManager = new ExternalProcessManager(_calcPanel);

        Button embedButton = new Button
        {
            Text = "嵌入計算器",
            Location = new Point(32010)
        };
        embedButton.Click += EmbedCalculator_Click;
        this.Controls.Add(embedButton);
    }

    private void EmbedCalculator_Click(object sender, EventArgs e)
    
{
        _processManager.EmbedProcess("calc.exe");
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    
{
        _processManager.CloseEmbeddedProcess();
        base.OnFormClosing(e);
    }
}

常見問題解決

窗口無法正確嵌入

// 確保等待窗口句柄創建
while (process.MainWindowHandle == IntPtr.Zero)
{
    System.Threading.Thread.Sleep(100);
    process.Refresh();
}

DPI縮放問題

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if (Environment.OSVersion.Version.Major >= 6)
    {
        SetProcessDPIAware();
    }
}

[DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();

窗口大小調整

protected override void OnResize(EventArgs e)
{
    base.OnResize(e);
    if (_embeddedProcess != null && !_embeddedProcess.HasExited)
    {
        WindowsAPI.MoveWindow(_embeddedProcess.MainWindowHandle, 
            00, _parentControl.Width, _parentControl.Height, true);
    }
}

總結

通過本文的詳細介紹和示例,你應該能夠在C# WinForms應用程序中成功實現外部程序的嵌入和控制。記住要注意進程管理、窗口處理、性能優化和安全性等關鍵方面。合理使用這些技術可以幫助你創建更強大和靈活的應用程序。

?

閱讀原文:原文鏈接


該文章在 2025/5/26 10:23:05 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 国产精品大战 | 国产亚洲视品在线 | 日本在线观看的免费 | 成人一级午夜激情网 | 人气电影| 国产精品福利社 | 国产又粗又猛 | 日本免费综合中文 | 97成人影视 | 日本成人一区 | 国产精品第144页 | 精品电影在线观看 | 日韩精品在线电影 | 日本a∨| 成人拍拍拍社区 | 国产亲子 | 欧美日韩综合精品网 | 吊钟乳在线91 | 欧洲高清视频在线 | 91制片一二三 | 国产片免费 | 精品一区二区国产 | 中文字幕在线第一页 | 国产一区在线激情 | 99sewo| 国产精品制服丝 | 青青草精品在线视 | 乱老熟女一区二 | 91福利合集| 国产狂喷潮在线播放 | 成人精品一 | 99热20| 国产精品色片免费 | 日本国产亚洲 | 国产素人搭讪在线 | 国产射精在线观看 | 欧亚a级一级 | 日韩精品二区三区 | 国产日韩在线看 | 91视频看看九色 | 91福利影院|