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!
Related
I have a button for which I set the KeyPress event.
this.myButton.KeyPress += new KeyPressEventHandler(this.myButtonEvent_keypress);
private void myButtonEvent_keypress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Space)
{
// do something
}
}
Now whenever the Space key is pressed, I get the event triggered. This part works fine.
But for some reason, the Enter key press is not triggering the KeyPress
event. Also Alt, Ctrl, Shift are not working.
How can I make the button receive Enter key press?
UPDATE:
I tried below too without any luck
this.myButton.MouseClick += new MouseEventHandler(myButton_Click);
When a Button has focus and you press Enter or Space the Click event raises.
So to handle Enter or Space it's enough to handle Click event and put the logic you need there.
So you just need to use button1.Click += button1_Click;
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
}
If you really want to know if Enter or Space was pressed, you can hanlde PreviewKeyDown event:
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if(e.KeyCode== Keys.Enter)
{
MessageBox.Show("Enter");
}
if (e.KeyCode == Keys.Space)
{
MessageBox.Show("Space");
}
}
Enter and space can be handled using click event.
this.myButton.Click += new EventHandler(myButton_Click);
The Button control in WinForms will eat Enter, Space, Tab, ESC, and a few other special key's press events. One method to intercept these events is to override Control.ProcessDialogKey. Or you can override IsDialogKey to say if a key should be handled as a special case.
A another option is to set KeyPreview = true on you parent Form. Then you can handle all KeyPress events at the Form level and use Form.ActiveControl if you need to see what control has Focus
I have an application and I want to start a countdown timer.
I created an EventHandler under the partial class:
event EventHandler startTimer;
And I wrote a function:
public void startTimerEvent(object sender, EventArgs e)
{
this.Invoke((MethodInvoker)delegate
{
timer.Start();
});
}
How can I register this to the EventHandler and where do I wire it up in my form?
To tie the event to the handler:
startTimer += startTimerEvent;
But I'm not really sure there isn't a better way to go about solving your general problem. If you could describe further what you're after, perhaps we could suggest a better way.
So you need to choose an event that will trigger your handler. Let’s say you have a button, and you want to handle its click event. You could write:
myButton.Click += new EventHandler(StartWhatEver);
Then you would have your StartWhatEver that does what you want.
private void StartWhatEver(object sender, EventArgs e)
{
// Do stuff...
}
Note: If you are working in VS2010, you can type myButton.Click += (with space) then double tap the 'Tab' key and this will create your handler for you automatically including the triggered method.
Hope this helps.
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 am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".
It just feels like there is a better way to do this. So the question is, is there?
I thinks that's the way to catch Key.Enter.
Also, you're code will be more readable if you use the KeyDown event instead of the KeyUp event.
If you only care about catching Key.Enter for a single control then your approach is correct.
You can also catch the Key.Enter for a group of related controls by using the KeyDown event of their container ("Event Bubbling").
Do you really want it in the textbox? I would put a onkeyup handler on the container (e.g. Grid, Canvas) to press the button anywhere on the form.
This will work if you use want to bind the Command property instead of using the Click event. Start by creating an event handler for Click (see below) and then in the KeyUp do:
private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter) SomeButton_Click(this, null);
}
private void SomeButton_Click(object sender, RoutedEventArgs e)
{
ICommand cmd = SomeButton.Command;
if (cmd.CanExecute(null))
{
cmd.Execute(null);
}
}
I use the following implementation when using the command pattern:
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
BindingExpression b = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (b != null)
b.UpdateSource();
ICommand cmd = SomeButton.Command;
if (cmd.CanExecute(null))
cmd.Execute(null);
}
}
When you press Enter, the data source of the textbox is not updated and the command uses an old value. Therefore you have to call UpdateSource before executing the command.
Of course you can catch the event on a higher level than the textbox.
Well, Im preaty new to Silverlight and I created HitEnter beahaviour for button which have one DependencyProperty Button.
And I manulay wire up Button and Behavior (in code behind) and then when enter is hit I inovke the command on the button.