I’m using a PasswordBox control in wpf.
I want to block space in the control, but i can’t find the way.
I tried to use a KeyDown event but the event isn’t working.
What is the best way to block space in the PasswordBox?
For WPF you should using PreviewKeyDown Based on docs occurs before the KeyDown event When a key is pressed while focus is on this control.
XAML:
<PasswordBox x:name="txtPasscode" PreviewKeyDown="txtPasscode_PreviewKeyDown"/>
and in behind :
private void txtPasscode_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space && txtPasscode.IsFocused == true)
{
e.Handled = true;
}
}
Also in C# native try this :
private void txtPasscode_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ') e.Handled = true;
}
The KeyDown event you're handling actually fires after the character added to the passwordbox. You can block it by handling PreviewKeyDown this way(KeyDown won't fire anymore if user pressed space):
private void passwordbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
e.Handled = true;
}
}
If you need to block an event you're going to use the event beginning with "Preview"(read more here).
Related
I have a Windows Form Application. I want some functions to work with the space key. But when I press the space key, the function I want is not working and it goes to the next form. (I did KeyPreview = true)
private void Form7_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
IEyeTracker eyeTracker = EyeTrackingOperations.FindAllEyeTrackers().FirstOrDefault();
GazeDataStop(eyeTracker);
}
}
Because:
1- If you have buttons, ... keydown won't work as form won't have focus anymore
2-you must handle the keydown so that it is not passed to ohter controls
Solution for 1:
set KeyPreview property of your form to true
Solution for 2:
set e.Handled = true:
private void Form7_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
if (e.KeyCode == Keys.Space)
{
IEyeTracker eyeTracker = EyeTrackingOperations.FindAllEyeTrackers().FirstOrDefault();
GazeDataStop(eyeTracker);
}
}
I want to handle crtl+click event in WPF XAML code behind. I registered KeyDown event and MouseDown event, but I am not able to register for them together. What is that I am missing.
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.LeftCtrl))
{
//do something
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 1)
{
//do something
}
}
Thanks,
RDV
Don't bother tracking Key Up/Down events--they're not reliable (e.g., user may switch windows between pressing and releasing). Just check Keyboard.Modifiers when you process the click.
If you only want to handle Ctrl+Click and not, for example, Ctrl+Shift+Click, then check Modifiers for an exact match:
if (e.ClickCount == 1 && Keyboard.Modifiers == ModifierKeys.Control) {
}
Otherwise, do a selective bitwise match:
if (e.ClickCount == 1 && (Keyboard.Modifiers & ModifierKeys.Control) != 0) {
}
Keyboard.Modifiers should generally be consistent: it won't reflect the release of the control key until after you process the mouse event, because all input events are processed in FIFO order.
Be sure to read up on bubbling versus tunneling events (e.g., MouseDown vs. PreviewMouseDown), and how events stop routing once they are marked as Handled.
As an alternative, you may be able to use a simple MouseGesture with a MouseAction of LeftClick and Modifiers of Control. It really depends on what your UI looks like, and whether you want a chance at handling the event before any descendant controls. Using a mouse gesture should work in (mostly) the same scenarios as handling the bubbling MouseDown event. But if you need to rely on tunneling events like PreviewMouseDown, then a gesture wouldn't work.
Do something like this, with a flag:
bool _isControlPressed = false;
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.LeftCtrl))
{
_isControlPressed = true;
}
}
private void Window_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.LeftCtrl))
{
_isControlPressed = false;
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 1 && _isControlPressed)
{
//do something
}
}
The _isControlPressed flag is set/unset in the key down/key up events. You can then use this flag in other methods to determine the key state.
I have added a keyPress event on a ListView. With a breakpoint on my event, I can see that most of the keys trigger the event. However, a few among which, the one I'm interested in (delete), just won't trigger my event.
Is that weird ? And no, there's no broken keys on my keyboard :D
private void listView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Delete)
{
ListView target = (ListView)sender;
if (target.SelectedIndices != null && target.SelectedIndices.Count > 0)
{
string ric = target.SelectedItems[0].SubItems[0].Text;
//target.Items.RemoveAt(target.SelectedIndices[0]);
ListModels.getInstance().getModel("Vols").removeRic(ric);
}
}
}
The reason for this is that the KeyPress event sends a character to the control based upon the character-key you press. However, as you'd expect, the delete key does not represent a character and is thus a non-character key.
Therefore using the KeyPress event will do nothing as you have noticed. You should use the KeyDown or KeyUp Events, either of which will work absolutely fine. The nuance being whether you want your event to fire upon pressing, or letting go of a key.
You'll want to use the KeyDown event for this.
In KeyDown use the condition as follows,
if (e.KeyCode == Keys.Delete)
{
// Your Logic....
}
Use keyDown instead; keyPress is something like a full keyDown + keyUp
The problem is that if you set EditMode property to EditOnEnter it won't fire. If you use EditOnKeyStrokeOfF2 it will fire the event
If you are looking for a solution where the user should only be able to choose from the defined items, then I believe you can do it with this:
private void DropDownRank_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
See this code:
private void Form1_Load(object sender, EventArgs e)
{
listView1.KeyUp += new KeyEventHandler(ListView_KeyUp);
}
/// <summary>鍵盤觸發 ListView 清單</summary>
private void ListView_KeyUp(object sender, KeyEventArgs e)
{
ListView ListViewControl = sender as ListView;
if (e.KeyCode == Keys.Delete)
{
foreach (ListViewItem eachItem in ListViewControl.SelectedItems)
{
ListViewControl.Items.Remove(eachItem);
}
}
}
I tried all the stuff mentioned above but nothing worked for me, so im posting what i actually did and worked, in the hopes of helping others with the same problem as me:
Add an event handler in the constructor:
public partial class Test
{
public Test()
{
this.RemoveHandler(KeyDownEvent, new KeyEventHandler(Test_KeyDown));
// im not sure if the above line is needed (or if the GC takes care of it
// anyway) , im adding it just to be safe
this.AddHandler(KeyDownEvent, new KeyEventHandler(Test_KeyDown), true);
InitializeComponent();
}
//....
private void Test_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
//your logic
}
}
}
I have a ComboBox with AutoCompleteMode = suggest and handle the KeyPress event like so:
private void searchBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
// do stuff
}
}
However, it does not catch the Enter key. It catches everything else since the autocomplete dropdown works perfectly.
I also tried the suggestion offered here : http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/2db0b540-756a-4a4f-9371-adbb92409806, set the form's KeyPreview property to true and put a breakpoint in the form's KeyPress event handler:
private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = false;
}
However, even the form's handler was not catching the enter key!
Any suggestions?
(If I disable the autocomplete, it catches the Enter key)
Difference between KeyDown and KeyPress
In your case the best you may do is use KeyDown event.
void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// Do stuff
}
}
Another interesting thing about KeyPress event is: it even catches Enter key with autocompete on if the combobox has no items! :-)
I want to capture delete key presses and do nothing when the key is pressed. How can I do that in WPF and Windows Forms?
When using MVVM with WPF you can capture keypressed in XAML using Input Bindings.
<ListView.InputBindings>
<KeyBinding Command="{Binding COMMANDTORUN}"
Key="KEYHERE" />
</ListView.InputBindings>
For WPF add a KeyDown handler:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
MessageBox.Show("delete pressed");
e.Handled = true;
}
}
Which is almost the same as for WinForms:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
MessageBox.Show("delete pressed");
e.Handled = true;
}
}
And don't forget to turn KeyPreview on.
If you want to prevent the keys default action being performed set e.Handled = true as shown above. It's the same in WinForms and WPF
I don't know about WPF, but try the KeyDown event instead of the KeyPress event for Winforms.
See the MSDN article on Control.KeyPress, specifically the phrase "The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events."
Simply check the key_press or Key_Down event handler on the specific control and check like for WPF:
if (e.Key == Key.Delete)
{
e.Handle = false;
}
For Windows Forms:
if (e.KeyCode == Keys.Delete)
{
e.Handled = false;
}
I tried all the stuff mentioned above but nothing worked for me, so im posting what i actually did and worked, in the hopes of helping others with the same problem as me:
In the code-behind of the xaml file, add an event handler in the constructor:
using System;
using System.Windows;
using System.Windows.Input;
public partial class NewView : UserControl
{
public NewView()
{
this.RemoveHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown));
// im not sure if the above line is needed (or if the GC takes care of it
// anyway) , im adding it just to be safe
this.AddHandler(KeyDownEvent, new KeyEventHandler(NewView_KeyDown), true);
InitializeComponent();
}
//....
private void NewView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
//your logic
}
}
}