我如何运行一些简单的C#code对于给定的关键preSS? [英] How do I run some simple C# code for a given keypress?
问题描述
我有一个XAML表单上的按钮调用 btnName_Click()
code在支持 CS
文件。
I have a button on a XAML form that calls the btnName_Click()
code in the backing cs
file.
我也想分配键盘快捷方式运行同样的code。基本上<大骨节病> CTRL 骨节病> + <大骨节病>&larr; 骨节病>或类似的东西。
I also want to assign a keyboard shortcut to run that same code. Basically CTRL + ← or something similar.
这需要考虑目前我在控制的工作(有例如一个TextBox,我要确保,如果我在那里我不会捕捉事件)。
This needs to work regardless of the control I'm currently in (there's a TextBox for example that I want to ensure doesn't capture the event if I'm in there).
我读了关于路由的命令,但似乎想了很多工作,为东西应该很简单。
I've read up on routed commands but that seems like a lot of work for something which should be simple.
有没有一种简单的方法来做到这一点还是需要建立路由命令?如果确实需要使用它们,什么是实现我想要的最简单的方法?
Is there an easy way to do this or do I need to create routed commands? If I do need to use them, what's the simplest way to achieve what I want?
推荐答案
让您的XAML为:
<StackPanel PreviewKeyDown="StackPanel_PreviewKeyDown">
<Button x:Name="btnName" Click="btnName_Click" Height="Auto" Width="Auto" Content="Name"></Button>
<TextBox x:Name="tb"></TextBox>
</StackPanel>
和你的CS为:
public MainWindow()
{
InitializeComponent();
}
private void btnName_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("This is from btnName");
}
private void StackPanel_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.Left)
{
btnName_Click(sender, new RoutedEventArgs());
e.Handled = true;
}
}
您应该把喜欢你的窗口中最顶端控制在 previewKeydown
事件,以便一旦<大骨节病>控制骨节病> + <大骨节病>&larr; < /骨节病>被击中只有窗口或顶部控制处理它并没有其他人。
You should put the PreviewKeydown
event on the topmost control like your window so that once Ctrl + ← is hit only the window or top control handles it and no one else.
previewKeyDown
是一个隧道的事件 - 它起源于最顶端的控制和下降到实际控制
PreviewKeyDown
is a tunneled event - it originates at the topmost control and goes down to actual control.
这篇关于我如何运行一些简单的C#code对于给定的关键preSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!