C# keypress doesn't capture 'delete' key - c#

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
}
}
}

Related

How to block space in passwordbox in wpf

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).

KeyDown KeyEventArgs won't work

I am trying to include HotKeys in my program but I don't know how to execute this code:
private void Form_KeyDown(object data, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
timer1.Stop();
}
}
Just copy&paste that code to your form (I find this usage easier)
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
timer1.Stop();
}
}
EDIT
BTW: Don't forget to set true to KeyPreview property of the form.
Have you bound that event? Sounds like it is not wired up.
public Form()
{
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
}
You can bind event that way, or doubleclick the KeyDown event in the Properties window in Visual Studio.
If you choose the point and click way, the event will bound in the Form.Designer.cs file.
The complete code constructor and method would look like this:
public Form()
{
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
}
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
timer1.Stop();
}
}
Per my comment:
I'm not sure about the Insert key, but you're looking for Mnemonics. On your form, use the "&" character before the character you want to shortcut. For example, on any button, menu, label etc... that says "Open", change the text to "&Open" and it will do what you want.
Edit: Keep in mind, this binds the Alt+yourCharacter key combination, not just the single key. If you're looking specifically to do special keys (insert, F1 etc...) you will need to implement a solution from the other answers (I think #QtX's solution will do what you want)

Prevent multiple firing of keydown events C#

I want to allow the user to send his message when he press enter in the textbox.
I went to search and im using the sample codes below.
Now the problem is when i press enter, the event is triggered more than once like about 4-5 times.
Someone else suggested to use keyup. I have tried keyup, keydown and keypress. All have the same problem.
How do i prevent it from firing the event more than once?
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Thank you!
You are adding the KeyUp event handler multiple times (inside the TextChanged handler); therefore, when Enter is pressed, the handler executes multiple times.
What you want to do here is add the KeyUp handler just once, inside your form's constructor, just after the InitializeComponent() call:
public MyForm()
{
// other code possibly here
InitializeComponent();
// and now add the event handler:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
This is because every time you change the text, the tbxAnswer_TextChanged is called/ fired you assign an action to the keyup event; if the text is changed 4 times then you assigned the keyup event 4 times and it increases every time you change the text.
try this out:
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
private void tbxAnswer_TextChanged(object sender, EventArgs e)
{
}
private void tbxAnswer_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyValue == (char)13)
{
MessageBox.Show("Hello");
}
}
Change your code to this
tbxAnswer.KeyUp -= tbxAnswer_KeyUp;
tbxAnswer.KeyUp += new KeyEventHandler(tbxAnswer_KeyUp);
In your code snippet, whenever the text of the TextBox changes, another eventhandler is added to the KeyUp handler. You should only add event handlers once (for instance, just after creating the textbox).
Sara and Jon have already provided the correct answer to your specific question. But if you want to go further and get a better understanding of how and when to use any particular key handling event take a look at my article Exploring Secrets of .NET Keystroke Handling. I explain and diagram when and where each event is useful, plus provide a KeystrokeSandbox application that lets you actually watch what happens!

Autocomplete on Combobox onkeypress event eats up the Enter key

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! :-)

How to capture delete key press in C#?

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
}
}
}

Categories

Resources