KeyDown KeyEventArgs won't work - c#

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)

Related

c# Starting events with hotkey?

private void MeretOK_Click(object sender, EventArgs e)
{
//code
}
private void MeretTB_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode==Keys.Enter)
{
MeretOK_Click();
}
}
How can I start an event with a hotkey?
(I know I can just copy the code there but that is ugly)
If I just copy the code and run it I hear a beep. Why?
First, you have to allow your form to handle key events globally (set the form KeyPreview property to true) and to mark your event as internally handled. Second, if the purpose of this code is to simulate the mouse click on a specific control (programmatic click), for example a button, there is an easier way to accomplish it:
private void MeretTB_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
myButton.PerformClick();
}
}

How do I create keyboard input in a wpf application?

I want to make a wpf application in c# that displays some text on screen, and where the user is supposed to write a response and press enter to submit the response. I don't want to use a textbox, since there is only one line for the text input in the window, and I don't want the user to have to click to select the textbox. I want the application to be mouse-free.
My question is: How do I make it so that when the user has written their answer, they can submit the response simply by pressing enter?
I have tried the following snippet of code which I found on a microsoft help website:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
doSomething();
}
}
I suppose I have to add some code elsewhere, but I'm not sure where or what I need to add.
If you want to make sure your window process every Enter key press without care what control is focused you can use PreviewKeyDown event:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//Process user input
e.Handled = true;
}
}
Of course if you are doing mvvm you can create a behavior to encapsulate the event handler:
public class WindowBehavior : Behavior<Window>
{
protected override void OnAttached()
{
AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
}
private void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
MessageBox.Show("Enter from Window");
e.Handled = true;
}
}
protected override void OnDetaching()
{
AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
}
I suggest you to read this article about bubble, tunneling and direct events basic for WPF events.
If you have a button that you're using for submit, you can easily set it as the default by using the IsDefault=true (wrote a tip about doing this and the cancel for the escape here.)
Other than that, you'll have to have somewhere to write it (yet you don't want a textbox? you can select it by default, or tab into it if you don't have the focus there), and you can handle the keydown to "catch" the Enter otherwise.

textBox Action Methods

I'm working on a program that allows the user to enter a barcode via scanner and then do stuff, and I've got most of it worked out, I just can't figure out which action method for textBox1 would allow me to do something when "Enter" was hit while in the textBox. I've looked at the description of most of the actions, and I can't find one that sounds like it would work.
Is there one that would work? Or do I just have to check every time a key is pressed?
You want the KeyDown / OnKeyDown or KeyUp/OnKeyUp event, just filter for the right key:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Enter)
{
// Do Something
}
}
Or in your case since your parent form is most likely subscribing to the TextBox event then you would add a method like the following using the designer:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Do Something
}
}
Keep in mind that what you are calling "Action Methods" are called Events.
Try this, using the KeyUp event:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DoSomething();
}
}
try handler the keypress event.
stop the handler and work better.
using System;
using System.Windows.Forms;
public class Form1: Form
{
public Form1()
{
// Create a TextBox control.
TextBox tb = new TextBox();
this.Controls.Add(tb);
tb.KeyPress += new KeyPressEventHandler(keypressed);
}
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar != (char)Keys.Enter)
{
e.Handled = true;
}
}
public static void Main()
{
Application.Run(new Form1());
}
}

Richtextbox deletes selected text

I have the following code:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
}
}
When I press the N key , the selected text is replaced with "n". I read this Selecting text in RichTexbox in C# deletes the text ,but it had no effects.
I am using Windows Forms.
Likely, you will need e.Handled = true; in this to stop the event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled.aspx
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.Handled = true;
}
}
Try it yourself:
Open up the editor, type some text, mark some of this text and press N. What happens? The marked text is replaced with n.
The same thing happens in your RichTextBox. Important to understand here is, that with the event you set up, you only add some functionality and leave the default event handling (handled by the OS) intact.
So with your code, on a key press you just do
richTextBox1.Select(1, 3);
which selects some characters and afterwards the default event handling kicks in. Thus there is some marked text which gets replaced with N.
So, you simply have to mark the event as handled by yourself. Not using the Handled-property, but with the SuppressKeyPress-property.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.SuppressKeyPress = true;
}
}
The documentation of Handled clearly states:
If you set Handled to true on a TextBox, that control will
not pass the key press events to the underlying Win32 text
box control, but it will still display the characters that the user typed.
Here is the official documentation of SuppressKeyPress.

C# keypress doesn't capture 'delete' key

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

Categories

Resources