Call a function when the key "space" is pressed in a window - wpf

I'm developing a board game and I would like to call a function when space is pressed in the window but I couldn't find answer to my problem during my searches.
Do you have an idea?

Lots of ways to do this. The easiest is to hook up an event handler (albeit not the most elegant). More elegant solutions involving commands can also be used though, depending on what controls you're using.
XAML
<Window KeyDown="MainWindow_OnKeyDown"
<!-- other properties -->
>
<!-- rest of your UI -->
</Window>
Code Behind
private void MainWindow_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
// do something
}
}

XAML:
<Window ...
PreviewKeyUp="Window_PreviewKeyUp" >
</Window>
Code behind:
// Use the PreviewKeyUp event to capture the keypress before
// any child controls that have focus handle the event
private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Space)
{
AFunction();
// to prevent the key press to bubble up to child controls that have focus
e.Handled = true;
}
}

Related

How to capture combination of keys( CTRL+ALT + SPACE) in WPF RichEdit control

i want to capture key combination such as ALT+CTL+SPACE in my RichEdit control in WPF.
You can add PreviewKeydown event for RichTextBox.
PreviewKeyDown="TextBox_OnPreviewKeyDown" in xaml
event handler in code behind as follows
private void TextBox_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.LeftAlt) &&
Keyboard.IsKeyDown(Key.Space))
{
// All keys were pressed
}
}
you can test when three keys are pressed.

Windows Phone/Silverlight: check whether a control has input focus

How to know whether a control such as TextBox has the input focus in a Windows Phone Silverlight app?
You have to use FocusManager
bool b = FocusManager.GetFocusedElement() == myTextbox;
There are events like GotFocus and LostFocus for controls.
If you subscribe to these events they automatically get called when your input receives or looses focus
you can use those events for your purpose.
XAML Declaration
<TextBox Name="myTextbox" GotFocus="myTextbox_GotFocus" />
and inside the cs
private void myTextbox_GotFocus(object sender, RoutedEventArgs e)
{
}
private void ContentPanel_LostFocus(object sender, RoutedEventArgs e)
{
}

The KeyDown event of a Simple style combo box is raised two times

I have simple win form application with the tab and combo box controls.
Combo box control has a style of "Simple".
Tab control has key down event.
When I press Enter key on the combo control it fires TWO key down events. If you change the combo style to any other, the key down event fires only one which it is something I expect.
Has anybody got any ideas why I am getting two key down events for single enter key press?
I have found similar issue on the Microsoft website, but that was related to .NET 1.0.
http://support.microsoft.com/kb/814970
It has probably something to do with the Enter key having pre-defined behavior for the Simple DropDown style.
You can try this work-around in the KeyDown event:
void comboBox1_KeyDown(object sender, KeyEventArgs e) {
e.SuppressKeyPress = true;
// do stuff
}
As you can guess, the KeyPress event won't fire now.
If you need to still process things in the KeyPress event, you can try this work-around:
void comboBox1_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char)Keys.Enter) {
e.Handled = true;
} else {
// do stuff
}
}
KeyPress from Combobox accepts just 'char' keys. For you purpose, please, use KeyDown event for combobox and e.Handled property.
Then your code will work and look like:
private void comboBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
comboBox2.KeyDown += new KeyEventHandler(comboBox2_SelectionChangeCommitted);
}
if (e.KeyCode != Keys.Enter)
{
e.Handled = false;
}
}

Silverlight: How to Prevent Routing a MouseMove Event from a Child Canvas to Its Parent Canvas

I have my XAML code:
<Canvas x:Name="mainCanvas" Width="200" Height="150" Background="LightGray"
MouseLeftButtonUp="mainCanvas_MouseLeftButtonUp"
MouseMove="mainCanvas_MouseMove">
<Canvas x:Name="topCanvas" Width="200" Height="100" Background="LightBlue"
MouseLeftButtonUp="topCanvas_MouseLeftButtonUp"
MouseMove="topCanvas_MouseMove">
</Canvas>
</Canvas>
and its code behind:
private void topCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("topCanvas_MouseLeftButtonUp");
e.Handled = true; // This can prevent routing to the mainCanvas
}
private void mainCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("mainCanvas_MouseLeftButtonUp");
}
private void topCanvas_MouseMove(object sender, MouseEventArgs e)
{
Debug.WriteLine("topCanvas_MouseMove");
// How to prevent routing to the mainCanvas?
// e.Handled = true does NOT exist in MouseEventArgs
}
private void mainCanvas_MouseMove(object sender, MouseEventArgs e)
{
Debug.WriteLine("mainCanvas_MouseMove");
}
My question is already in the comments.
How to prevent routing the MouseMove event from the topCanvas (the child canvas) to the mainCanvas (parent canvas)?
Thanks.
Peter
Try setting the IsHitTestVisible property of your Canvas. With that property set accordingly mouse events will go either "through" your control or will be caught by it.
Hope this is what you need.
You can try comparing e.OriginalSource in mainCanvas's MouseMove Event and exit the Sub if it wasn't originated from the mainCanvas.
private void mainCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (sender != e.OriginalSource)
return;
}
In replying to your comment in a little more detail. According to the UIElement.MouseMove Event MSDN link.
Controls that inherit MouseMove can provide handling for the event
that acts as handler for all instances, by overriding the OnMouseMove
method. As with direct handling of the event, there is no Handled
property available, so OnMouseMove cannot be implemented in such a way
that it suppresses further handling of the event through the Handled
technique.
and this link states:
This event creates an alias for the Mouse.MouseMove attached event for
this class
Which brings us to this link on AttachedEvents which states.
Extensible Application Markup Language (XAML) defines a language
component and type of event called an attached event. The concept of
an attached event enables you to add a handler for a particular event
to an arbitrary element rather than to an element that actually
defines or inherits the event. In this case, neither the object
potentially raising the event nor the destination handling instance
defines or otherwise "owns" the event.
So as I see it, your only option is to code around it.
The functionality is called "Event Bubbling". You can stop it using below code:
jQuery:
event.stopPropagation();
Ref: http://api.jquery.com/event.stopPropagation/
You can also try below code:
e.stopPropagation(); //to prevent event from bubbling up
e.preventDefault(); //then cancel the event (if it's cancelable)
Ref: http://stackoverflow.com/questions/1967537/how-to-stop-event-bubbling-with-jquery-live
Thanks,
Ravi Verma

How can I disable the default RichTextBox command for Ctrl+1?

Snoop shows that the command is "ApplySingleSpace", but when I try disabling it via the method described in this article . Like this:
<RichTextBox.CommandBindings>
<CommandBinding
Command="ApplySingleSpace"
CanExecute="BlockTheCommand"/>
</RichTextBox.CommandBindings>
.
private void BlockTheCommand(object sender,
CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
My app crashes because there is no ApplySingleSpace command. ApplySingleSpace is not in the EditingCommands either.
What am I missing?
Unfortunately that will not work for
me. The reason I am trying to disable
the command is that I have a
KeyBinding in a higher nested view
that is not firing because the CTRL+1
gesture is being swallowed by the
richtextbox which has keyboardfocus.
How about overwriting that KeyBinding with a custom command that does what you want instead of trying to somehow disable it?
<RichTextBox.InputBindings>
<KeyBinding Command="local:YourCommands.Cmd1" Gesture="CTRL+1" />
<RichTextBox.InputBindings>
Taken from this question.
Using the code from this answer
How can I programmatically generate keypress events in C#?
to refire all events on PreviewKeyDown other than those you want handled by the richtextbox seems to work for me. (I only need Ctrl-C for copy). Of course you could make it so it only refires Ctrl-1 if that's what you need.
private void logKeyHandler(object sender, KeyEventArgs e)
{
if (!(Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C))
{
e.Handled = true;
var routedEvent = Keyboard.KeyDownEvent;
this.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromDependencyObject(this),
0,
e.Key) { RoutedEvent = routedEvent }
);
}
}
What about trying with the gesture instead...
<RichTextBox.InputBindings>
<KeyBinding Command="BlockTheCommand" Gesture="CTRL+1" />
</RichTextBox.InputBindings>

Resources