WndProc не вызывается во встроенном процессе в wpf

Следуя инструкциям в:

Как запустить приложение внутри приложения 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>

Сначала я получу приложения, нажав кнопку "Получить приложения", а затем нажмите "Пуск". Результат будет выглядеть следующим образом:

введите описание изображения здесь

Но только одно размещенное приложение принимает пользовательский ввод. (В этом примере это 1-е приложение, обведенное красным, которое может иметь пользовательский ввод). Другие 2 не принимают пользовательский ввод. Ничего не срабатывает при нажатии на другие 2 приложения.

Я знаю, что я не справлялся со многими ситуациями. Но это не повлияло на проблему, с которой я столкнулся в настоящий момент, я предположил. Это простое приложение (не настоящее приложение), которое я написал, и я надеюсь, что кто-то сможет воспроизвести ту же ошибку, что и я.

Есть что-то, что я делаю не так? Или я что-то пропустил? Любые предложения будут ценны. Заранее спасибо!

1 ответ

Решение

Я нашел решение этой проблемы,

то есть использовать WindowsFormsHost разместить консольное приложение, как в этом примере.

Я создал System.Windows.Forms.Panel и установить его как Child из WindowsFormsHost и еще раз добавить его в детей Wrap Panel,

Так или иначе, все размещенные приложения могут получать пользовательские входные данные.

Что касается того, почему, используя HwndHost а также Border размещать консольные приложения, не получать пользовательские входные данные, я до сих пор не знаю, почему.

Но я думаю это потому что:

  1. Я установил стиль окна размещенного приложения на Child что делает его неспособным получать входные данные пользователя. (Я знаю, что где-то читал, но где забыл)
  2. WndProc только получает сообщения формы, он не имеет доступа к / перехватывать сообщения, поступающие в консоли.

Вот две причины, по которым я могу придумать, которые приводят к тому, что размещенные приложения не могут получать пользовательские входные данные.

Поправьте меня если я ошибаюсь.

С уважением,
Кай

Другие вопросы по тегам