c# Textbox KeyEventArgs - each letter is checked multiple times - c#

I am checking the keycode for a textbox, and I want a certain task to be performed when the user presses Enter.
It has been working perfectly, but the task that I am trying to perform now, usually is done using a mouse click. So on the OK on that task (a FolderBrowserDialog), it keeps calling the dialog control.
Oddly enough, even though the debugger shows me into the if branch, for e it shows {KeyData = LButton|MButton|Back}, but KeyValue is still 13...
I think it may be that the textbox remembers its last entry... True ?
In my troubleshooting, I have added a boolean variable so I only go into FolderBrowser when it is true, I have tried to add and delete a space from the textbox after the Browse, and even clear the textbox... Each attempt seemed to make things worse.
It seemed that I was in a quasi-infinite loop - yet it would go away after lots of "ok"'s, and stepping through, I found that for every letter I type in the textbox, I spend 4 to 5 rounds in the CheckKeys. I don't understand why... Or how to fix it.
I added a "e.Handled" which did me no good.
Here's the code:
private void txtDir_TextChanged(object sender, EventArgs e)
{
this.txtDir.KeyUp += new System.Windows.Forms.KeyEventHandler(CheckKeys);
}
private void CheckKeys(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (sender == txtDir && txtDir.Text != "" && System.IO.Directory.Exists(txtDir.Text))
{
btnBrowse_Click(this, e);
}
}
}
Why am I going through this check so many times ? Can I add a different test ? Am I doing something wrong ? (nothing is set as default action, for form or textbox...)
Thank you.

In your code you added handler for KeyUp at TextChanged Event. so, When TextChanged new handler will be added for KeyUp Event. Thats why multiple time each letter is checked. put Handler at Form load event.
e.g. If I have entered five letter in TextBox so, 5 Handler will be added for KeyUp. means Number of KeyUp Event Handler equals to number of time TextChanged Event called.
this.txtDir.KeyUp += new System.Windows.Forms.KeyEventHandler(CheckKeys);
this add new handler for KeyUp event. So, when this line execute new handler will be added.
By putting Handler at Form Load event, you can solve multiple letter checked problem.
Try with,
private void FormLoad(object sender, EventArgs e)
{
this.txtDir.KeyUp += new System.Windows.Forms.KeyEventHandler(CheckKeys);
}
private void CheckKeys(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (sender == txtDir && txtDir.Text != "" && System.IO.Directory.Exists(txtDir.Text))
{
btnBrowse_Click(this, e);
}
}
}
And one more thing As I understand your code, you want to execute btnBrowse_Click if Enter pressed in TextBox control. But Enter key not handled with KeyUp event you need KeyDown Event handler to handle Enter key.
Code:
private void FormLoad(object sender, EventArgs e)
{
this.txtDir.KeyDown += new System.Windows.Forms.KeyEventHandler(CheckKeys);
}
private void CheckKeys(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (sender == txtDir && txtDir.Text != "" && System.IO.Directory.Exists(txtDir.Text))
{
btnBrowse_Click(this, e);
}
}
}

Use KeyDown event instead of TextChanged and write down e.Handle = True in it.
write down following code in your textBox.KeyDown event:
if (e.KeyCode == Keys.Enter)
{
if (sender == txtDir && txtDir.Text != "" && System.IO.Directory.Exists(txtDir.Text))
{
e.Hanlde = true; //it will be close enter keydown handling at this time
btnBrowse_Click(this, e);
}
}

Replaced TextChanged with KeyDown directly and it works again !
(on a side note, I still don't understand why each letter is tested several times...)
Edit: Now after reading the accepted answer, I do understand...

Related

Capture Tab KeyUp on a winrt textbox

I am building a XAML app (winrt) to be used in enterprise. Some forms in the app can be complex: some inputs gets shown/hidden depending on other inputs. I would like to control the tab key navigation using a behavior on all inputs (TextBox, PasswordBow, ComboBox...) to optimize the user activity.
I subscribed to the KeyUp event of the TextBox but the event is not raised when the user strikes the Tab key. As a consequence, the next element in the visual tree is given keyboard focus.
I found not method to override like the winform's IsInputKey.
How can I subscribe to the use of the Tab key on a TextBox?
Is looks like the newly focus element receives the KeyUp event.
What I did is subscribe to the KeyDown event, checked for the Tab key and marked the event as handled.
protected override void OnAttached()
{
var textBox = (TextBox)this.AssociatedObject;
textBox.KeyDown += this.OnKeyDown;
textBox.KeyUp += this.OnKeyUp;
// don't forget to unsubscribe in OnDetached
}
private void OnKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Tab && !e.Handled)
{
e.Handled = this.Work(sender, e);
}
}
private void OnKeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key != VirtualKey.Tab && !e.Handled)
{
e.Handled = this.Work(sender, e);
}
}
Here is the method that does the focusing work. The code was in OnKeyUp before I knew how to do.
/// <returns>true if an action has been performed (focus next or execute command)</returns>
private bool Work(object sender, KeyRoutedEventArgs e)
{
var isEnterKey = e.Key == VirtualKey.Enter;
var isTabKey = e.Key == VirtualKey.Tab;
if (/* there is something else to focus */)
{
// focus it
return true;
}
return false;
}
My problem was that the Tab virtual key wasn't being received in the KeyUp event, while other keys (Esc,Enter, alphanumeric keys) were. I just changed it to a KeyDown with the same handler. The difference seems to be imperceptible to the user.

TextBox KeyPress event doesn't fire

I have a Form with nine TextBox controls. Each one has a KeyPress event handler that fires on Enter/Return and more.
The fifth TextBox(Kategorie) and sixth (Ort) don't fire. The others do. The code is:
private void tb_Kategorie_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("works");
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
tb_Ort.Focus();
}
else if (e.KeyChar == (char)Keys.Escape)
{
tb_Kategorie.Text = escSpeicher;
tb_Kategorie.SelectAll();
}
}
The event handler is set in the Designer and in designer.cs. The button and the code are not copy/pasted. Can someone tell me where the problem is?
// You Can Use Key Down method here
private void tb_Kategorie_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("works");
if (e.KeyCode== Keys.Enter || e.KeyCode== Keys.Return)
{
tb_Ort.Focus();
}
else if (e.KeyCode== Keys.Escape)
{
tb_Kategorie.Text = escSpeicher;
tb_Kategorie.SelectAll();
}
}
// try this
Try to set the Form.KeyPreview property to True
It is something with the Autocomplete Source.
This is the same problem like in
Autocomplete on Combobox onkeypress event eats up the Enter key
It is not really solved, but a nice workaround

KeyUp event firing from next control

I've 5 buttons in my windows application. When I click arrow keys the focus changing between buttons, then only
KeyUp
event firing. How to stop this?
Subscribe to the PreviewKeyDown event instead.
Occurs before the KeyDown event when a key is pressed while focus is on this control.
As you move through the buttons, the sender parameter will contain the previously selected button.
I found a solution that should work for you, adapted from here. Apparently, MS made the decision that the arrow keys wouldn't trigger the KeyDown event, so you can't cancel them.
One workaround is to specify that your arrow keys are normal input keys, like any other key. Then the KeyDown event will fire and you can cancel the button press if you want.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
e.IsInputKey = true;
}
private void button1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
You may want to read the other answers and comments in that post to see what would work best in your situation.
Answer for your question in comment
void button1_LostFocus(object sender, EventArgs e)
{
button1.Focus();
}
To prevent Up from moving focus from a Button you have to utilize at least 3 methods:
bool _focus;
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Up)
_focus = true;
}
private void button1_KeyUp(object sender, KeyEventArgs e)
{
_focus = false;
}
private void button1_Leave(object sender, EventArgs e)
{
if(_focus)
button1.Focus(); // or (sender as Control)
}
Trick is to use flag when user press Up and to return focus in Leave. You have to unflag in KeyUp, otherwise it would be impossible to change focus (by pressing Tab to example).
You could possible unflag in Leave, I didn't test it.

Stop the 'Ding' when pressing Enter

I have a very simple Windows Forms Application. And, in Windows (or, atleast Windows Forms Applications), when you press Enter while inside a Single-line TextBox Control, you hear a Ding. It's an unpleasent sound, that indicated you cannot enter a newline, because it is a single-line TextBox.
This is all fine. However, in my Form, I have 1 TextBox, and a Search Button. And I am allowing the user to Perform a search by pressing Enter after they've finished typing, so they don't have to use the mouse to click the Search Button.
But this Ding sound occurs. It's very annoying.
How can we make it so just that sound doesn't play at all in my Form?
#David H - Here's how I'm detecting the enter pressing:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Perform search now.
}
}
It works for me:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//Se apertou o enter
if (e.KeyCode == Keys.Enter)
{
//enter key is down
this.doSomething();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
The SuppressKeyPress is the really trick. I hope that help you.
Check out the Form.AcceptButton property. You can use it to specify a default button for a form, in this case for pressing enter.
From the docs:
This property enables you to designate
a default action to occur when the
user presses the ENTER key in your
application. The button assigned to
this property must be an
IButtonControl that is on the current
form or located within a container on
the current form.
There is also a CancelButton property for when the user presses escape.
Try
textBox.KeyPress += new KeyPressEventHandler(keypressed);
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true; //this line will do the trick
}
}
Just add e.SuppressKeyPress = true; in your "if" statement.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//If true, do not pass the key event to the underlying control.
e.SuppressKeyPress = true; //This will suppress the "ding" sound.*/
// Perform search now.
}
}
You can Use KeyPress instead of KeyUp or KeyDown its more efficient
and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
and say peace to the 'Ding'
Use SuppressKeyPress to stop continued processing of the keystroke after handling it.
public class EntryForm: Form
{
public EntryForm()
{
}
private void EntryTextBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
// do some stuff
}
else if(e.KeyCode == Keys.Escape)
{
e.Handled = true;
e.SuppressKeyPress = true;
// do some stuff
}
}
private void EntryTextBox_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// do some stuff
}
else if(e.KeyCode == Keys.Escape)
{
// do some stuff
}
}
}
On WinForms the Enter key causes a Ding sound because the form property AcceptButton is not specified.
If you don't need an AcceptButton the ding sound can be suppressed by setting the form KeyPreview to true and enter the following KeyPress event:
private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
e.Handled = true;
}
No matter what control is active, there will be no more ding sound when pressing the Enter key. Since the key event proccessing order is KeyDown, KeyPress and KeyUp the Enter key will still work for the KeyDown events for the controls.
I stumbled on this post while trying to handle a KeyDown this worked for me.
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
btnLogIn.PerformClick()
End If
Supressing the Key Press stops the event from being sent to the underlying control. This should work if you're manually handling everything that the enter key will be doing within that textbox. Sorry about the Visual Basic.
$("#txtSomething").keypress(function (e) {
if (e.which == 13) {
e.Handled = true; //This will prevent the "ding" sound
//Write the rest of your code
}
});
There is a very little chance anyone gets to this answer but some other answers are truly scary. Suppressing event on KeyDown kills 2 additional events in one strike. Setting e.Handled property to true is useless in this context.
The best way is to set Form.AcceptButton property to the actual Search Button.
There is also another way of utilizing Enter key - some people may want it to act as TAB button. To do that, add a new Button, set its Location property outside of the Form area (i.e. (-100, -100)) - setting Visible property to false may disable Button handlers in some cases. Set Form.AcceptButton property to your new button. In Click event handler add following code
this.SelectNextControl(ActiveControl, true, true, true, true)
Now, you may want to transfer focus only when focus it on TextBox you may want to either test ActiveControl type or use e.Supress property in event handlers of controls not meant to use Enter as TAB
That's it. You don't even need to capture e.KeyCode
Set your Search button's IsDefault property to true. This will make it a default button and it will be auto-clicked when Enter is pressed.
Well I lived with this problem long enough and looked it up here.
After thinking about this for quite some time and wanting the simplest way to fix it I came up with the easiest but not so elegant way to fix it.
Here is what I did.
Put 2 invisible buttons "Ok" and "Cancel" on the form.
Set the AcceptButton and CancelButton Property on the form to the invisible buttons.
Added no code to the buttons!
This solved all the secondary problems listed in this thread including the ToolStripMenu. My biggest complaint was the BindingNavigator, when I would enter a record number into the Current position to navigate to and pressed enter.
As per the original question in which the programmer wanted a search function when the enter button was pressed I simply put the search code in the invisible OK Button!
So far this seems to solve all problems but as we all know with Visual Studio, something will probably crop up.
The only other possible elegant way I could think of would be to write a new keystroke handling class which is way to much work for most of my projects.
You can set your textbox multi-line to true then handle the Enter key press.
private void yourForm_Load(object sender, EventArgs e)
{
textBox1.Multiline = true;
}
//then write your TextBox codes
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// doSomething();
}
}
i changed the textbox properties for an multiline textbox and it works for me.
Concerning the e.SuppressKeyPress = true; solution, it works fine by itself. Setting SuppressKeyPress to true also sets Handled to true, so there's no need to use e.Handled= true;
void RTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
//do ...
bool temp = Multiline;
Multiline = true;
e.Handled = true;
Multiline = temp;
}
}

Catching Ctrl + C in a textbox

Despite me working with C# (Windows Forms) for years, I'm having a brain fail moment, and can't for the life of me figure out how to catch a user typing Ctrl + C into a textbox.
My application is basically a terminal application, and I want Ctrl + C to send a (byte)3 to a serial port, rather than be the shortcut for Copy to Clipboard.
I've set the shortcuts enabled property to false on the textbox. Yet when the user hits Ctrl + C, the keypress event doesn't fire.
If I catch keydown, the event fires when the user presses Ctrl (that is, before they hit the C key).
It's probably something stupidly simple that I'm missing.
Go ahead and use the KeyDown event, but in that event check for both Ctrl and C, like so:
if (e.Control && e.KeyCode == Keys.C) {
//...
e.SuppressKeyPress = true;
}
Also, to prevent processing the keystroke by the underlying TextBox, set the SuppressKeyPress property to true as shown.
Key events occur in the following order:
KeyDown
KeyPress
KeyUp
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
Control is a noncharacter key.
You can check with this line of code:
if (e.KeyData == (Keys.Control | Keys.C))
I had a problem catching Ctrl + C on a TextBox by KeyDown. I only got Control key when both Control and C were pressed. The solution was using PreviewKeyDown:
private void OnLoad()
{
textBox.PreviewKeyDown += OnPreviewKeyDown;
textBox.KeyDown += OnKeyDown;
}
private void OnPreviewKeyDown( object sender, PreviewKeyDownEventArgs e)
{
if (e.Control)
{
e.IsInputKey = true;
}
}
private void OnKeyDown( object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C) {
textBox.Copy();
}
}
D'oh! Just figured it out. Out of the three possible events, the one I haven't tried is the one I needed! The KeyUp event is the important one:
private void txtConsole_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C | Keys.Control))
{
_consolePort.Write(new byte[] { 3 }, 0, 1);
e.Handled = true;
}
}
If you want to catch such combinations of keys in KeyPress Event look at this table here:
http://www.physics.udel.edu/~watson/scen103/ascii.html
in Non-Printing Characters section you can see the Dec numbers for each combination.
For example, Dec number for Ctrl + C is 3. So you can catch it in KeyPress Event like this:
private void btnTarget_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 3) // if it is not Ctrl + C
{
// do something
}
}
Try the following: capture the up arrow and down arrow events. When you detect down arrow for CTRL, set a flag; when you detect up arrow, reset the flag. If you detect the C key while the flag is set, you have Ctrl+C.
Edit. Ouch... Jay's answer is definitely better. :-)
I don't know if it's because some change in newer version or because I am trying to use this on ListBox, but there is no e.Control in KeyEventArgs e that I get from KeyDown.
I had to work around solution, I came up with this (it's not the prettiest one, but it works fine):
private List<Key> KeyBuff = new List<Key>();
private void ListBox_KeyDown(object sender, KeyEventArgs e)
{
if (!KeyBuff.Exists(k => k == e.Key))
KeyBuff.Add(e.Key);
if (KeyBuff.Exists(k => k == Key.LeftCtrl || k == Key.RightCtrl) &&
KeyBuff.Exists(k => k == Key.C))
{
// Desired detection
Clipboard.SetText(SelectedText);
}
}
private void ListBox_KeyUp(object sender, KeyEventArgs e)
{
KeyBuff.Clear();
}
For me, it's not working with KeyDown event so I tried with PreviewKeyDown and it's worked.
private void txt_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.C)
{
Clipboard.SetText(txt.SelectedText);
}
}

Categories