WPF WinForm Interop:多级WinForm应用程序中的快捷方式处理

时间:2019-06-01 18:10:27

标签: c# .net wpf winforms winforms-interop

我需要处理一些快捷键,并且使用ElementHost和WindowsFormsHost具有以下应用程序结构(无法更改此结构)

Winform App --> (ElementHost) --> Wpf Control --> (WindowsFormsHost) --> WinForm Control

WinForm Control覆盖下,ProcessCmdKey(ref Message msg, Keys keyData)级别处理的快捷方式很少。

还存在全局快捷键,这些全局快捷键在WinForm App级别使用ProcessCmdKey(ref Message msg, Keys keyData)覆盖进行处理(例如: F3

问题

WinForm Control处于焦点时,按 F3 /任意键只会触发WinForm Control的{​​{1}}方法进入相应控件的按下事件。 预处理事件未达到ProcessCmdKey的{​​{1}}或Wpf Control的{​​{1}}。因此,OnPreviewKeyDown没有机会使用该键。

其他观察结果

  • 如果焦点Winform App,则在事件发生时按任意键都会触发
ProcessCmdKey
  • 如果WPF控件托管在WPF应用程序中,则事件将按预期工作。
Winform App
  • 我尝试引发WindowsFormsHost控件的Wpf Control事件 来自 Wpf Control's OnPreviewKeyDown() --> Winform App's ProcessCmdKey() 的ProcessCmdKey()方法。 WinForm Control's ProcessCmdKey() -> WPF App Window's PreviewKeyDown() -> WpfControl's PreviewKeyDown() 在WPF层触发,但不调用PreviewKeyDown中的Winform Control

  • 我尝试使用PreviewKeyDown将消息从ProcessCmdKey发送到Winform App的消息队列,但是没有成功。

类似问题

WinFormApp

Winform App

WPFControl.xaml

SendMessage

WpfControl.cs

WinForm Control

WinControl

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ElementHost host = new ElementHost();
            host.Dock = DockStyle.Fill;
            host.Child = new WpfControl();
            this.Controls.Add(host);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }  
<UserControl x:Class="App.WpfControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:App"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="124*" />
            <ColumnDefinition Width="388*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="2*" />           
        </Grid.RowDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="value1" Height="28" HorizontalAlignment="Left" Name="value1" VerticalAlignment="Top" />
        <TextBox Grid.Row="0" Grid.Column="1" Height="23" HorizontalAlignment="Left" Name="textBox1" VerticalAlignment="Top" Width="257" />

        <WindowsFormsHost Grid.Column="1" Grid.Row="2" Height="90" HorizontalAlignment="Left" Name="windowsFormsHost1" VerticalAlignment="Top" Width="307">
            <local:WinControl></local:WinControl>
        </WindowsFormsHost>

    </Grid>
</UserControl>

0 个答案:

没有答案