SendInput是我找到的唯一一个可以通过它的方法。从
this
链接。
PInvoke发送输入这是
模拟输入的官方方式。它
通过所有
预期的代码路径,并且是
无法与实际输入区分开。
一个简单的使用方法是
InputSimulator
来自CodePlex。
添加对InputSimulator.dll的引用我们可以这样做
private bool m_waitingForFocusVisualStyle = false;
private void ListBoxItem_GotFocus(object sender, RoutedEventArgs e)
{
if (m_waitingForFocusVisualStyle == false)
{
m_waitingForFocusVisualStyle = true;
InputSimulator.SimulateKeyDown(VirtualKeyCode.TAB);
InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.SHIFT, VirtualKeyCode.TAB);
}
else
{
m_waitingForFocusVisualStyle = false;
}
}
但这可能不太理想,原因很多(例如,将Shift+Tab移到ListBoxItem)
一个更好的主意可能是删除ListBoxItem的FocusVisualStyle,然后像这样在ControlTemplate中添加自己的FocusVisualStyle。(从Blend复制并从标准FocusVisualStyle添加“FocusVisualStyle”)
<ListBox ...>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template" Value="{StaticResource ListBoxItemTemplate}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<ControlTemplate x:Key="ListBoxItemTemplate" TargetType="{x:Type ListBoxItem}">
<Grid>
<Rectangle Grid.ZIndex="1"
Name="focusVisualStyle"
StrokeThickness="1"
Stroke="Black"
StrokeDashArray="1 2"
SnapsToDevicePixels="true"
Visibility="Hidden"/>
<Border x:Name="Bd"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="focusVisualStyle" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
</MultiTrigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>