0

按照以下说明:

如何在 wpf 应用程序中运行应用程序?

并在 MSDN 中的演练中 ( https://msdn.microsoft.com/en-us/library/ms752055.aspx )

我已经设法在 wpf 中托管我的控制台应用程序。(注意:要托管的应用程序超过 2 个)

在 ControlHost.cs

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

namespace Try
{
public class ControlHost : HwndHost
{
    private static List<Process> _procList = new List<Process>();
    IntPtr hwndControl;
    int hostHeight, hostWidth;
    string filePath;

    internal const int
    WS_CHILD = 0x40000000,
    GWL_STYLE = -16,
    WS_CAPTION = 0x00C00000,
    WS_THICKFRAME = 0x00040000;

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

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

    [DllImport("user32")]
    private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);

    [DllImport("user32.dll", EntryPoint = "DestroyWindow", CharSet = CharSet.Unicode)]
    internal static extern bool DestroyWindow(IntPtr hwnd);

    public ControlHost(double height, double width, string filePathName)
    {
          hostHeight = (int)height;
          hostWidth = (int)width;
          filePath = filePathName;
    }

    protected override HandleRef BuildWindowCore(HandleRef hwndParent)
    {
        Process _process = new Process();
        _process.StartInfo.FileName = filePath;
        _process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
        _process.Start();
        _procList.Add(_process);

        // The main window handle may be unavailable for a while, just wait for it
        while (_process.MainWindowHandle == IntPtr.Zero)
        {
            Thread.Yield();
        }

        hwndControl = _process.MainWindowHandle;

        int style = GetWindowLong(hwndControl, GWL_STYLE);
        style = style & ~((int)WS_CAPTION) & ~((int)WS_THICKFRAME); // Removes Caption bar and the sizing border
        style |= ((int)WS_CHILD); // Must be a child window to be hosted

        SetWindowLong(hwndControl, GWL_STYLE, style);
        SetParent(hwndControl, hwndParent.Handle);

        this.InvalidateVisual();

        HandleRef hwnd = new HandleRef(this, hwndControl);
        return hwnd;
    }

    protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        handled = false;
        return IntPtr.Zero;
    }

    protected override void DestroyWindowCore(HandleRef hwnd)
    {
        DestroyWindow(hwnd.Handle);
        if (_procList != null)
        {
            foreach (Process p in _procList)
            {
                if (p != null)
                {
                    try
                    {
                        while (!p.HasExited)
                        {
                            p.Refresh();
                            p.CloseMainWindow();
                            p.Kill();
                            Thread.Sleep(10);
                        }
                    }
                    catch
                    {

                    }
                }
            }
        }
    }

    public void Stop(IntPtr Hwnd)
    {
        HandleRef hwnd = new HandleRef(this, Hwnd);

        DestroyWindow(hwnd.Handle);
        if (_procList != null)
        {
            foreach (Process p in _procList)
            {
                if (p != null)
                {
                    try
                    {
                        while (!p.HasExited)
                        {
                            p.Refresh();
                            p.CloseMainWindow();
                            p.Kill();
                            Thread.Sleep(10);
                        }
                    }
                    catch
                    {

                    }
                }
            }
        }
    }
}
}

MainWindow.xaml.cs中:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
   using System.Windows.Shapes;
    using Microsoft.Win32;

namespace Try
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string[] appsList;
        private List<ControlHost> ctrlHostList = new List<ControlHost>();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ControlHost appsControl;
            Border appsBorder;
            foreach (string app in appsList)
            {
                appsBorder = new Border();
                appsBorder.Height = double.NaN;
                appsBorder.Width = double.NaN;
                appsBorder.BorderBrush = Brushes.Silver;
                appsBorder.BorderThickness = new Thickness(1);
                appsControl = new ControlHost(appsBorder.ActualHeight, appsBorder.ActualWidth, app);
                ctrlHostList.Add(appsControl);
                appsBorder.Child = appsControl;
                WP_Apps.Children.Add(appsBorder);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog _openFileDlg = new OpenFileDialog();
            _openFileDlg.Multiselect = true;

            if (_openFileDlg.ShowDialog() == true)
            {
                appsList = _openFileDlg.FileNames;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            foreach(ControlHost CH in ctrlHostList)
            {
                CH.Stop(CH.Handle);
            }
        }
    }
}

最后在MainWindow.xaml中:

<Window x:Class="Try.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="1502" Width="1500" ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen" WindowState="Maximized" >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="76*"/>
            <ColumnDefinition Width="671*"/>
        </Grid.ColumnDefinitions>
        <Button Content="Start" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Height="20" Click="Button_Click"/>
        <Button Content="GetApps" HorizontalAlignment="Left" Height="21" Margin="10,54,0,0" VerticalAlignment="Top" Width="74" Click="Button_Click_1"/>
        <ScrollViewer Grid.Column="1">
            <WrapPanel Name="WP_Apps" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" />
        </ScrollViewer>
        <Button Content="Stop" HorizontalAlignment="Left" Margin="10,99,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_2"/>

    </Grid>
</Window>

首先,我将通过单击“获取应用程序”按钮而不是单击“开始”来获取应用程序。结果将如下所示:

在此处输入图像描述

但只有一个托管应用程序接受用户输入。(在这个例子中,它是第一个应用程序,用红色圈出的可以有用户输入)另外 2 个不接受任何用户输入。单击其他 2 个应用程序时不会触发任何内容。

我知道我没有处理过很多情况。但这并没有影响我目前遇到的问题,我想。这是我编写的一个简单的应用程序(不是真正的应用程序),我希望有人能够重现与我相同的错误。

有什么我做错了吗?还是我错过了什么?任何建议将不胜感激。提前致谢!

4

1 回答 1

0

我找到了解决这个问题的方法,

WindowsFormsHost用于托管控制台应用程序,如本 例所示

我创建了 aSystem.Windows.Forms.Panel并将其设置为 aChildWindowsFormsHost再次将其添加到 a 的子项中Wrap Panel

不知何故,所有托管应用程序都能够接收用户输入。

至于为什么,使用HwndHostBorder托管控制台应用程序,不接收用户输入,我仍然不知道为什么。

但我认为是因为:

  1. 我将托管应用程序的窗口样式设置为Child使其无法接收用户输入。(我知道我在某个地方读过它,但忘记在哪里)
  2. WndProc只接收表单消息,它无权访问/捕获控制台中的消息。

这是我能想到的导致托管应用程序无法接收用户输入的两个原因。

如我错了请纠正我。

最好的问候,

于 2015-06-16T15:07:13.110 回答