我在WPF中发现WindowsFormsHost
的一个非常奇怪的行为。我发现如果一个WPF控件没有WindowsFormsHost
作为子控件,那么IsKeyboardFocusWithinChanged
fires properly - 只要WPF控件获得或失去焦点,就会触发它,并且变量{ {1}}按预期切换(当控件获得焦点时IsKeyboardFocusWithin
,失去焦点时true
。
但是,如果我在WPF中托管false
,那么片刻之后,WPF母控件和WindowsFormHost
子控件都不再触发IsKeyboardFocusWithinChanged
事件。
我在MSDN文档中找不到或为什么这样,有什么原因?
这是我的代码:
MainWindow.xaml
WindowsFormHost
MainWindow.xaml.cs
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" IsKeyboardFocusWithinChanged="Window_IsKeyboardFocusWithinChanged">
<Grid Name="grid1">
</Grid>
</Window>
当涉及public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
host = new System.Windows.Forms.Integration.WindowsFormsHost();
var mtbDate = new System.Windows.Forms.MaskedTextBox("00/00/0000");
host.Child = mtbDate;
host.IsKeyboardFocusWithinChanged += Host_IsKeyboardFocusWithinChanged;
grid1.Children.Add(host);
}
private void Host_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(host.IsKeyboardFocusWithin.ToString()+" blah");
}
private System.Windows.Forms.Integration.WindowsFormsHost host;
private void Window_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(IsKeyboardFocusWithin.ToString());
}
}
的行被注释掉时,只要控件获得焦点,WindowsFormHost
就是IsKeyboardFocusWithin
,而当控件失去焦点时,true
就会被false
。
当包含WindowsFormHost
的行时,IsKeyboardFocusWithin
为true
,直到我点击该控件,然后host.IsKeyboardFocusWithin
变为false
,并且IsKeyboardFocusWithin
也变为false
,然后,无论我做什么,IsKeyboardFocusWithinChanged
事件都不会再被触发。
答案 0 :(得分:3)
优化以前的解决方案,以支持WindowsFormsHost
中的多个Window
元素。此外,如果IsKeyboardFocusWithin
属性为true
,则更新样式以突出显示具有绿色边框的聚焦控件。
<强> MainWindow.xaml 强>
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="325">
<Window.Resources>
<ResourceDictionary>
<Style TargetType="Border">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BorderBrush" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Child.IsKeyboardFocusWithin}" Value="True">
<Setter Property="BorderBrush" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Button x:Name="hiddenBtn" Height="1" Width="1" />
<StackPanel Grid.Column="0" x:Name="leftPanel" Margin="5">
<Label HorizontalContentAlignment="Right">Start Date</Label>
<Label HorizontalContentAlignment="Right">End Date</Label>
<Label HorizontalContentAlignment="Right">Phone Number</Label>
<Label HorizontalContentAlignment="Right">Zip Code</Label>
</StackPanel>
<StackPanel Grid.Column="1" x:Name="rightPanel" Margin="5">
</StackPanel>
</Grid>
</Window>
<强> MainWindow.xaml.cs 强>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GenerateControls();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
}
private const int WM_KILLFOCUS = 0x0008;
private const int WM_ACTIVATEAPP = 0x001c;
private const int WM_PARAM_FALSE = 0x00000000;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Handle messages...
if (msg == WM_KILLFOCUS)
{
Console.WriteLine(wParam + " " + lParam);
//suppress kill focus message if host has keyboardfocus, else don't
var hosts = FindVisualChildren<WindowsFormsHost>(this);
var focusedControlHwnd = wParam.ToInt32();
if(focusedControlHwnd != 0)
{
handled = hosts.Any(x => x.Child.Handle.ToInt32() == focusedControlHwnd);
}
}
else if (msg == WM_ACTIVATEAPP && wParam.ToInt32() == WM_PARAM_FALSE)
{
//now the kill focus could be suppressed event during window switch, which we want to avoid
//so we make sure that the host control property is updated
var hosts = FindVisualChildren<WindowsFormsHost>(this);
if (hosts.Any(x => x.IsKeyboardFocusWithin))
hiddenBtn.Focus();
}
return IntPtr.Zero;
}
private void GenerateControls()
{
System.Windows.Forms.MaskedTextBox maskedTextBox;
System.Windows.Forms.Integration.WindowsFormsHost host;
host = new System.Windows.Forms.Integration.WindowsFormsHost();
maskedTextBox = new System.Windows.Forms.MaskedTextBox("00/00/0000");
host.Child = maskedTextBox;
rightPanel.Children.Add(new Border() { Child = host });
host = new System.Windows.Forms.Integration.WindowsFormsHost();
maskedTextBox = new System.Windows.Forms.MaskedTextBox("00/00/0000");
host.Child = maskedTextBox;
rightPanel.Children.Add(new Border() { Child = host });
host = new System.Windows.Forms.Integration.WindowsFormsHost();
maskedTextBox = new System.Windows.Forms.MaskedTextBox("(000)-000-0000");
host.Child = maskedTextBox;
rightPanel.Children.Add(new Border() { Child = host });
host = new System.Windows.Forms.Integration.WindowsFormsHost();
maskedTextBox = new System.Windows.Forms.MaskedTextBox("00000");
host.Child = maskedTextBox;
rightPanel.Children.Add(new Border() { Child = host });
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
}
<强>截图强>
正如Hans Passant在评论中提到的,这种行为是由于WindowsFormsHost
和MaskedTextBox
具有不同的Hwnd(s)而引起的。
第一次单击主机控件时,子控件将获得焦点,并且正确设置了IsKeyboardFocusedWithin。但是一旦子控件获得焦点,操作系统就会注意到Hwnd的差异并将kill-focus消息发送到WPF窗口 - 这反过来又将IsKeyboardFocusedWithin设置为false。
您可以做的是在WPF主窗口中添加WndProc
挂钩,并禁止kill-focus消息 - 仅当主机控件的IsKeyboardFocusedWithin
值为true时。
但是,有一个副作用 - 当您从WPF窗口切换时,主机控件的IsKeyboardFocusedWithin
值可能保持为真。为了解决这个问题,您可以使用简单的遍历技巧在发送窗口禁用消息时移动焦点,从而根据当前状态更新属性IsKeyboardFocusedWithin。
源代码示例: 我使用StackPanel而不是Grid,以显示TextBox
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
host = new System.Windows.Forms.Integration.WindowsFormsHost();
var mtbDate = new System.Windows.Forms.MaskedTextBox("00/00/0000");
host.Child = mtbDate;
host.IsKeyboardFocusWithinChanged += Host_IsKeyboardFocusWithinChanged;
stackPanel1.Children.Add(host);
textBox1 = new TextBox();
stackPanel1.Children.Add(textBox1);
textBox2 = new TextBox();
stackPanel1.Children.Add(textBox2);
}
private void Host_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(host.IsKeyboardFocusWithin.ToString() + " blah");
textBox1.Text = $"Host.IsKeyboardFocusedWithin = {host.IsKeyboardFocusWithin}";
}
private System.Windows.Forms.Integration.WindowsFormsHost host;
private TextBox textBox1;
private TextBox textBox2;
private void Window_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine(IsKeyboardFocusWithin.ToString());
textBox2.Text = $"Window.IsKeyboardFocusedWithin = {IsKeyboardFocusWithin}";
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
}
private const int WM_KILLFOCUS = 0x0008;
private const int WM_ACTIVATEAPP = 0x001c;
private const int WM_PARAM_FALSE = 0x00000000;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Handle messages...
if (msg == WM_KILLFOCUS)
{
//suppress kill focus message if host has keyboardfocus, else don't
handled = host.IsKeyboardFocusWithin;
}
else if (msg == WM_ACTIVATEAPP && wParam.ToInt32() == WM_PARAM_FALSE)
{
//now the kill focus could be suppressed event during window switch, which we want to avoid
//so we make sure that the host control property is updated by traversal (or any other method)
if (host.IsKeyboardFocusWithin)
{
host.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
return IntPtr.Zero;
}
}
而且,结果将如下所示:
有焦点
无焦点