In my WPF application a "global" search box appears when hitting Ctrl+Space. It behaves like Spotlight in Mac OS when hitting Command+Space.
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static RoutedCommand OpenSpotlight { get; set; } = new RoutedCommand();
public MainWindow()
{
OpenSpotlight.InputGestures.Add(new KeyGesture(Key.Space, ModifierKeys.Control));
}
private void OpenSpotlight_Execute(object sender, ExecutedRoutedEventArgs e)
{
// Code which opens the search box ...
}
}
MainWindow.xaml
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:MainWindow.OpenSpotlight}" Executed="OpenSpotlight_Execute"/>
</Window.CommandBindings>
Works fine, except one problem: when any button is focused, hitting Ctrl+Space triggers the button to be clicked because Space key is being hit.
Is there any way to omit this behaviour? I think of changing/removing the focus globally when Ctrl key is hit but don't know how this can be implemented ...
Instead of using a RoutedCommand and a CommandBinding, you could just handle the PreviewKeyDown event:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PreviewKeyDown += OnPreviewKeyDown;
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space
&& (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
{
e.Handled = true;
// Code which opens the search box ...
}
}
}
This solution doesn't require you to add anything to the XAML markup.
I haven't tried this, but seems quite logical to me.
You can handle the KeyDown and/or PreviewKeyDown event of a button and skip the Space press. Something like this could work :
private void GlobalButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
e.Handled = true;
}
Wondering how you'ld do this for all the buttons? Here's a function to find a control of a given type:
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;
}
}
}
}
Simply loop through the buttons on window_load or similar events:
foreach (Button btn in FindVisualChildren<Button>(this))
{
btn.KeyDown += GlobalButton_PreviewKeyDown;
btn.PreviewKeyDown += GlobalButton_PreviewKeyDown;
}
Hopefully this helps.
Related
So, apparently I had some problem when handling keys such as F10 or F11.
I want to move the focus from current textbox into another textbox, but not in one particular textbox. So, I wrote some code to handle key:
private void checkKeys(KeyEventArgs e)
{
if (e.KeyCode == Keys.F10)
{
buyerName.Focus();
}
else if (e.KeyCode == Keys.F11)
{
discount.Focus();
}
}
But, if I put this into individual textbox, which kinda hassle to me. Is there any method to listen key whether in global userControl or textbox?
Edit : here's my structure that I want to ask :
Form-
|-User Control
|-TextBox
Edit 2 : here's some image might help img
To use a global keyboard listener in Winforms, you just need to add a handler to KeyUp action for the main form itself:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F10)
{
textBox1.Focus();
e.Handled = true; //To use F10, you need to set the handled state to true
} else if (e.KeyCode == Keys.F11)
{
textBox2.Focus();
}
}
Then make sure that the KeyPreview property on the main form is set to True.
The issue with the application freezing when pressing F10 is because it is waiting for another consecutive action. To bypass this simply set the Handled property on the keyevent to TRUE. This releases the unresolved event.
This is my entire form class, refactored to use a helper method as you are refering to. This works fine. But you have to make sure that the KeyPreview property on your form is True, unless your keypresses will not be matched to your event handlers.
namespace KeyTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
CheckKeys(e);
}
private void CheckKeys(KeyEventArgs e)
{
if (e.KeyCode == Keys.F10)
{
textBox1.Focus();
e.Handled = true;
}
else if (e.KeyCode == Keys.F11)
{
textBox2.Focus();
e.Handled = true;
}
}
}
}
Now in your comment you are mentioning a UserControl, if you want that, then you need to create an instance method on your UserControl class, and pass the event to that from your global keyboard event handler on your main form.
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public void HandleKeys(KeyEventArgs e)
{
if (e.KeyCode == Keys.F10)
{
textBox1.Focus();
e.Handled = true;
}
else if (e.KeyCode == Keys.F11)
{
textBox2.Focus();
e.Handled = true;
}
}
}
Then on your main form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
CheckKeys(e);
}
private void CheckKeys(KeyEventArgs e)
{
uc1.HandleKeys(e); //Instance method on your user control.
}
}
This then works as intended.
As pointed out in one of the comments, a better way would be to override the ProcessCmdKey method on the Form base class. This would be done like so:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
userControl11.HandleKeys(keyData); // method on the userControl to handle the key code.
base.ProcessCmdKey(ref msg, keyData);
return true;
}
}
The handler on the UserControl stays more or less the same:
public void HandleKeys(Keys keys)
{
if (keys == Keys.F10)
{
nameTB.Focus();
} else if (keys == Keys.F11)
{
emailTB.Focus();
}
}
Whether this is a more correct way of doing it, I am unsure of. They certainly both accomplish the same result. The documentation shows the first method in for handling keyboard events at the form level here:
How to handle keyboard input
But states here that the ProcessCmdKey method is to provide additional handling of shortcuts and MDI accellerators.
ProcessCmdKey
I will leave that up to you to decide what is the best for your scenario. But keep it in to show how you would use it should you choose to.
You can hook up to the KeyUp event of your form.
That way, any key pressed while your form is focused will be send to you (if the control didn't handle the key).
Thanks to #Espen and #reza-aghaei for handling keys into main form. Unfortunately, I still didn't managed find a way to focus to designated textbox inside a UserControl. However, I make some dirty method which kinda crappy and un-efficient by searching child control from it's parent
//MainForm.cs
if(yourUserControl.Name)//Do some check for targeted userControl, if null can cause NullReferenceException
{
if (e.KeyCode == Keys.F10)
{
this.Controls.Find("textboxName", true).First().Focus();
e.Handled = true;
}
}
in my uwp app I just added a new page and navigated to it, and I have nothing on that page just the default grid. but I am trying to recieve keydown events which is not firing up by any key at all. I have also put keydown to the grid on xaml and to the page in code behind, but it is still not firing up I have assured that with break points.
xaml
<Grid KeyDown="VideoPageKeyDown">
</Grid>
code behind
public sealed partial class VideoPlay : Page
{
public VideoPlay()
{
this.InitializeComponent();
KeyDown += VideoPageKeyDown;
}
private void VideoPageKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.GamepadDPadDown
|| e.Key == VirtualKey.GamepadLeftThumbstickDown)
{
//VideoMenuGrid.Visibility = Visibility.Visible;
//await VideoMenuGrid.Offset(200f, 0f, 1000, 0).StartAsync();
}
else if (e.Key == VirtualKey.GamepadDPadUp
|| e.Key == VirtualKey.GamepadLeftThumbstickUp)
{
//await VideoMenuGrid.Offset(0f, 0f, 1000, 0).StartAsync();
//VideoMenuGrid.Visibility = Visibility.Collapsed;
}
}
}
Controls like the grid that do not get focus will not receive the event directly. If there is another control on top of it might pass the event to the grid because it is an routed event. Thy using the coreWindow keyDown event instead.
public sealed partial class VideoPlay : Page
{
public VideoPlay()
{
this.InitializeComponent();
//Add this line
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}
void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
{
//todo
}
}
This question already has answers here:
How to clear the text of all textBoxes in the form?
(10 answers)
Clear all TextBox in Window
(1 answer)
Closed 6 years ago.
Is there a way to clear textboxes at once when they have been renamed as txtFName, txtMName etc... They may have variety of names beginning with txt. Is this possible? Something like
private void btnReset_Click(object sender, EventArgs e)
{
txtFname.Clear();
txtLName.Clear();
txtUsername.Clear();
txtPasswrd.Clear();
/*So many textboxes to be cleared*/
}
to be replaced with
private void ClearTextboxes(object obj)
{
/*codes to clear textboxes*/
}
and then we can call it in the button click event
private void btnReset_Click(object sender, EventArgs e)
{
ClearTextboxes();
txtFname.Focus();
}
this method clear all textbox from WinForm
void ClearTextboxes(System.Windows.Forms.Control.ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearTextboxes(ctrl.Controls);
}
}
and you can call it
private void btnReset_Click(object sender, EventArgs e)
{
ClearTextboxes();
txtFname.Focus();
}
You can iterate through all textbox in your VisualTree like this:
foreach (TextBox txtBx in FindVisualChildren<TextBox>(this))
{
txtBx.Clear();
}
FindVisualChildren :
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;
}
}
}
}
As an argument you can pass any parent it can be StackPanel, or Grid or whole window.
One way using event is:
using System;
using System.Windows.Forms;
namespace textBoxs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Subscribe();
}
private event Action ClearAll;
void Subscribe()
{
ClearAll += tbA.Clear;
ClearAll += tbB.Clear;
ClearAll += tbC.Clear;
}
private void button1_Click(object sender, EventArgs e)
{
ClearAll();
}
}
}
I have a User control with a list box.
This User control located on my window.
how can I detect and get selected item from list box in user control?
I previously tried this but when i select an item from list box e.OriginalSource return TextBlock type.
private void searchdialog_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
//This return TextBlock type
var conrol= e.OriginalSource;
//I Want something like this
if (e.OriginalSource is ListBoxItem)
{
ListBoxItem Selected = e.OriginalSource as ListBoxItem;
//Do somting
}
}
Or there is any better way that I detect list box SelectionChanged in From My form?
I think the best soution would be to declare an event on your user control, that is fired whenever the SelectedValueChanged event is fired on the listbox.
public class MyUserControl : UserControl
{
public event EventHandler MyListBoxSelectedValueChanged;
public object MyListBoxSelectedValue
{
get { return MyListBox.SelectedValue; }
}
public MyUserControl()
{
MyListBox.SelectedValueChanged += MyListBox_SelectedValueChanged;
}
private void MyListBox_SelectedValueChanged(object sender, EventArgs eventArgs)
{
EventHandler handler = MyListBoxSelectedValueChanged;
if(handler != null)
handler(sender, eventArgs);
}
}
In your window, you listen to the event and use the exposed property in the user control.
public class MyForm : Form
{
public MyForm()
{
MyUserControl.MyListBoxSelectedValueChanged += MyUserControl_MyListBoxSelectedValueChanged;
}
private void MyUserControl_MyListBoxSelectedValueChanged(object sender, EventArgs eventArgs)
{
object selected = MyUserControl.MyListBoxSelectedValue;
}
}
there are a few ways to handle this:
Implement the SelectionChanged event in your usercontrol, and raise a custom event that you handle in your window:
//in your usercontrol
private void OnListBoxSelectionChanged(object s, EventArgs e){
if (e.AddedItems != null && e.AddedItems.Any() && NewItemSelectedEvent != null){
NewItemsSelectedEvent(this, new CustomEventArgs(e.AddedItems[0]))
}
}
//in your window
myUserControl.NewItemsSelected += (s,e) => HandleOnNewItemSelected();
If you use binding or any form of MVVM, you can use a DependencyProperty to bind the selected item to an object in your viewmodel
//in your usercontrol:
public static readonly DependencyProperty CurrentItemProperty =
DependencyProperty.Register("CurrentItem", typeof(MyListBoxItemObject),
typeof(MyUserControl), new PropertyMetadata(default(MyListBoxItemObject)));
public LiveTextBox CurrentItem
{
get { return (MyListBoxItemObject)GetValue(CurrentItemProperty ); }
set { SetValue(CurrentItemProperty , value); }
}
//in your window xaml
<MyUserControl CurrentItem={Binding MyCurrentItem} ... />
Possible Duplicate:
How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?
I want to close the windows in my wpf project when the user clicks the escape button. I don't want to write the code in every window but want to create a class which can catch the when the user press the escape key.
Option 1
Use Button.IsCancel property.
<Button Name="btnCancel" IsCancel="true" Click="OnClickCancel">Cancel</Button>
When you set the IsCancel property of a button to true, you create a
Button that is registered with the AccessKeyManager. The button is
then activated when a user presses the ESC key.
However, this works properly only for Dialogs.
Option2
You add a handler to PreviewKeyDown on the window if you want to close windows on Esc press.
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
}
private void HandleEsc(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
Close();
}
Here is a button-less solution that is clean and more MVVM-ish. Add the following XAML into your dialog/window:
<Window.InputBindings>
<KeyBinding Command="ApplicationCommands.Close" Key="Esc" />
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandBinding_Executed" />
</Window.CommandBindings>
and handle the event in the code-behind:
private void CloseCommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
if (MessageBox.Show("Close?", "Close", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
this.Close();
}
One line to put after InitializeComponent():
PreviewKeyDown += (s,e) => { if (e.Key == Key.Escape) Close() ;};
Please note that this kind of code behind does not break MVVM pattern since this is UI related and you don't access any viewmodel data. The alternative is to use attached properties which will require more code.
You can create a custom DependencyProperty:
using System.Windows;
using System.Windows.Input;
public static class WindowUtilities
{
/// <summary>
/// Property to allow closing window on Esc key.
/// </summary>
public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.RegisterAttached(
"CloseOnEscape",
typeof(bool),
typeof(WindowUtilities),
new FrameworkPropertyMetadata(false, CloseOnEscapeChanged));
public static bool GetCloseOnEscape(DependencyObject d)
{
return (bool)d.GetValue(CloseOnEscapeProperty);
}
public static void SetCloseOnEscape(DependencyObject d, bool value)
{
d.SetValue(CloseOnEscapeProperty, value);
}
private static void CloseOnEscapeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Window target)
{
if ((bool)e.NewValue)
{
target.PreviewKeyDown += Window_PreviewKeyDown;
}
else
{
target.PreviewKeyDown -= Window_PreviewKeyDown;
}
}
}
private static void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (sender is Window target)
{
if (e.Key == Key.Escape)
{
target.Close();
}
}
}
}
And use it your windows' XAML like this:
<Window ...
xmlns:custom="clr-namespace:WhereverThePropertyIsDefined"
custom:WindowUtilities.CloseOnEscape="True"
...>
The answer is based on the content of the gist referenced in this answer.
The InputBinding options here are nice and flexible.
If you want to use an event handler, be aware that the Preview events happen quite early. If you have a nested control that should take the Esc key for its own purposes, stealing it at the window level may brake that control's functionality.
Instead you can handle the event at the window level only if nothing else wants to with:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && e.Key == Key.Escape && Keyboard.Modifiers == ModifierKeys.None)
{
this.Close();
}
}