C # Keyboard shortcuts stopped working after invoking second XAML window

I have software that uses several XAML windows for different instances: for example, to export some information, I created secondary XAML windows with a different format than the parent program. They work great.

My problem is that if I use my software without calling any of these additional XAML windows, shortcuts work very well. But as soon as I call this new XAML window, the shortcuts no longer work. I need to restart the program so that they return.

Any clue to this behavior? Also, I have not yet been able to create shortcuts like CTRL + Letter. I saw a lot of codes, it seems pretty straight forward, but they just don't work ...

code

private void Window_KeyDown(object sender, KeyEventArgs e) { Key key = e.Key; if ((key == Key.Left) && previousButton.IsEnabled) button_PreviewMouseDown(previousButton, null); else if ((key == Key.Right) && nextButton.IsEnabled) button_PreviewMouseDown(nextButton, null); //New Label else if (key == Key.L) //else if (key == Key.LeftAlt && e.Key.ToString() == "L") NewLabel_Click(sender, e); // Begin Event else if (key == Key.B) BeginEvent_Click(sender, e); // End Event else if (key == Key.E) EndEvent_Click(sender, e); // Delete Label else if (key == Key.K) DeleteLabel_Click(sender, e); else if (key == Key.R) // Delete Event DeleteEvent_Click(sender, e); // Edit Label else if (key == Key.I) EditLabel_Click(sender, e); // Edit Event else if (key == Key.F) EditEvent_Click(sender, e); } 

EDIT 1

I found out that as soon as I call up a popup with C #, just saying โ€œEvent Created OKโ€, the shortcuts come to life again!

 MessageBox.Show("Event Created"); 

Any idea why this might happen?

+5
source share
1 answer

Another way to do this is to use RoutedCommands . With RoutedCommand, you assign KeyGestures .

Example

 /// <summary> /// Save Log command /// </summary> public static readonly RoutedCommand SaveLog = new RoutedCommand("SaveLog", typeof(Commands), new InputGestureCollection { new KeyGesture(Key.S, ModifierKeys.Control,"Save log contents to a file. (Ctl+S)") }); 

Assign RoutedCommand in your xaml

  <Button Style="{StaticResource LoggingWindowSaveLogButton}" Command ="{x:Static local:Commands.SaveLog}" /> 

Bind the command to the window

  <!-- Command Bindings--> <Window.CommandBindings> <CommandBinding Command="{x:Static local:Commands.SaveLog}" Executed="SaveLogCommand" CanExecute="SaveLogCommandCanExecute"/> </Window.CommandBindings> 

Then we implement SaveLogCommandCanExecute and SaveLogCommand

if SaveLogCommandCanExecute returns false , it will automatically disable any GUI to which RoutedCommand is bound.

Keep in mind that there MUST have focus in the window with the key binding.

0
source

Source: https://habr.com/ru/post/1246460/


All Articles