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
}
}
}
Related
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).
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);
}
}
My enter key events won't do anything...not even show a simple textbox when pressing Enter in a textbox.
I am new to c# and coding in general.
Interestingly, my visual studio won't let some things go through like MessageBox.Show... It makes me do System.Windows.MessageBox.Show. Just in case this is a clue to what the problem may be...
Here is what I have...
private void textBoxPartNumber_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == System.Windows.Forms.Keys.Enter)
{
//textBoxQuantity.Focus();
System.Windows.MessageBox.Show("Testing 123");
System.Windows.Forms.SendKeys.Send("{TAB}");
e.Handled = true;
e.SuppressKeyPress = true;
}
}
TextBox property AcceptsReturn
<TextBox AcceptsReturn="true"/>
Use
if (e.KeyCode == System.Windows.Forms.Keys.Return)
Instead :)
If you're using WPF then it appears your event signature is incorrect. Try something like this:
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//Do something
}
}
The KeyEventArgs class and Key enum are in the System.Windows.Input namespace in the PresentationCore assembly.
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! :-)