Form KeyUp and KeyDown events to change variables - c#

In my application I have:
private bool _clear = true;
This boolean is used to see if a textbox should be cleared or not when user enters a new text into it (by pressing on a TreeNode in a TreeView).
Then I have these two events for my form:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control)
{
_clear = false;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control)
{
_clear = true;
}
}
I want it somehow when user is holding the CTRL key, clear be FALSE and when CTRL is released, clear goes back to TRUE.
Obviously the code I wrote here, does not work! what can be wrong and/or is there a better way?

It's a simple fix, as when you release the key, the KeyUp event does not receive any info of the key released itself, so just set the property to true:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
_clear = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control)
{
_clear = false;
}
}
If you want to see it work in real time, add a label to your form and add this under each setting of the '_clear' variable:
label1.Text = _clear.ToString();
Per your comment, change the second code block to:
if (e.KeyData.ToString() == "ControlKey, Control")
{
_clear = false;
}
else if(other shortcut conditionals go here or on other else if's)
{
_clear = true;
}
The only time this conditional will hold true is when control is held by itself. The else case is there for the purpose of setting _clear to true when you press ctrl followed by another key, due to the fact that as soon as you press control, it will fire the KeyDown event.
Based on this change, as long as you take care of the key presses following that if statement, (such as else if()'s), you will not need to set anything in the KeyUp event.
See my answer here to the intricacies of keys and their properties if you want some more in-depth info.
Edit #3 :
As long as you set the _clear to true on the first line in each conditional, you should be able to avoid the problem you are facing in your comment:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData.ToString() == "ControlKey, Control")
{
_clear = false;
}
else if(e.KeyData.ToString() == "O, Control")
{
_clear = true;
//Do other stuff here, such as opening a file dialog
}
}

It is much easier if you do this the other way around. Check if the CTRL key is down in the treeview's event. Something like this:
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
if ((Control.ModifierKeys & Keys.Control) == Keys.Control) {
// Control key is down, do something...
}
}

You need to change the KeyPreview property of your form to True.

Related

C# custom ENTER key behaviour

I have a small projet in which I want several buttons to behave differently when Clicked or Ctrl+Clicked. To achieve that, each of those buttons has this kind of function attached to their Click() event :
private void Button1_Click(object sender, EventArgs e)
{
int value = 10 //default value
bool boool = false;
if (ModifierKeys == Keys.Control)
{
using (var form = new NUP_Popup(0, value, value, "maximum ?"))
{ //creates a simple window that allows user to change the value of 'value'
form.ShowDialog();
if (form.DialogResult == DialogResult.OK)
{
value = form.retVal;
boool = true;
}
else return;
}
}
//do stuff here, either with default or user value
}
Now, Clicking or Ctrl+Clicking behaves as intended with this function. My problem is that this behaviour doesn't apply when my buttons are activated using the Enter key : Enter key alone triggers the "normal" behaviour but Ctrl+Enter does nothing (button is not activated).
I already have overriden the ProcessDialogKey() function to close the window when Escape is pressed, so I thought I could use it to make Enter key presses trigger the Click() event function :
protected override bool ProcessDialogKey(Keys keyData) //Allows quit when Esc is pressed
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
if (keyData == Keys.Return)
{
this.OnClick(new EventArgs());
}
return base.ProcessDialogKey(keyData);
}
And that's where I'm stuck. Of course this doesn't do anything but I don't really have an idea of what to type inside my second condition to make it work.
Maybe I'm using the wrong approach ? Can someone point me in the right direction to do it ?
Assuming you placed a Label with ID Label1 and a button with ID Button1, following will do:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "Button Clicked";
if (Control.ModifierKeys == Keys.Control) label1.Text += " with Ctrl";
}
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\n') button1_Click(sender, new EventArgs());
}
to your solution, simply add a KeyPress event to your Button1 and apply following code inside the keypress event Button1_KeyPress:
if (e.KeyChar == '\n') Button1_Click(sender, new EventArgs());
Okay, so I finally found a working solution by adding this to my overriden ProcessDialogKey() method :
if (keyData == (Keys.Enter | Keys.Control))
{
(this.ActiveControl as Button).PerformClick();
}
I don't know if it qualifies as "clean" code, but it has the merit of fulfilling my 2 requirements : making Ctrl+Enter function as Ctrl+Click without having to declare 2 methods per Button.
I found a solution that enables you to either click Enter or Ctrl+Enter:
private void txtIP_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\n' || e.KeyChar == '\r') btnStart_Click(sender, new EventArgs());
}

Perform action while key is pressed

In my program I would need that an action is perfomed while a key is pressed. I have already searched but the solutions either were not for c#, neither for forms or I couldnt understand them.
Is there a proper and easy solution to this?
EDIT: I am using WinForms and I want that while the form is focussed and a key is pressed an action is repeatedly performed.
First off, you need to provide a bit more information and if possible some code you already tried. But nevertheless I'll try. The concept is relatively easy, you add a timer to your form, you add key_DOWN and key_UP events (not key pressed). You make a bool that resembles if key is currently pressed, you change its value to true on keydown and false on keyup. It will be true while you hold the key.
bool keyHold = false;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (keyHold)
{
//Do stuff
}
}
private void Key_up(object sender, KeyEventArgs e)
{
Key key = (Key) sender;
if (key == Key.A) //Specify your key here !
{
keyHold = false;
}
}
private void Key_down(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == Key.A) //Specify your key here !
{
keyHold = true;
}
}
**If you're trying to make a simple game on forms and you're struggling with the input delay windows has (press and hold a key, it will come up once, wait and then spam the key) This solution works for that (no pause after the initial press).
You can try this.
In the Key down event you set the bool 'buttonIsDown' to TRUE and start the method 'DoIt' in an Separate Thread.
The code in the While loop inside the 'DoIt' method runs as long the bool 'buttonIsDown' is true and the Form is on Focus.
It stops when the Key Up event is fired or the Form loose the focus.
There you can see the 'buttonIsDown' is set to false so that the While loop stops.
//Your Button Status
bool buttonIsDown = false;
//Set Button Status to down
private void button2_KeyDown(object sender, KeyEventArgs e)
{
Key key = sender as Key;
if (key == Key.A)
buttonIsDown = true;
//Starts your code in an Separate thread.
System.Threading.ThreadPool.QueueUserWorkItem(DoIt);
}
//Set Button Status to up
private void button2_KeyUp(object sender, KeyEventArgs e)
{
Key key = sender as Key;
if (key == Key.A)
buttonIsDown = false;
}
//Method who do your code until button is up
private void DoIt(object dummy)
{
While(buttonIsDown && this.Focused)
{
//Do your code
}
}

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

Not able to capture Enter key in WinForms text box

When the user is entering a number into a text box, I would like them to be able to press Enter and simulate pressing an Update button elsewhere on the form. I have looked this up several places online, and this seems to be the code I want, but it's not working. When data has been put in the text box and Enter is pressed, all I get is a ding. What am I doing wrong? (Visual Studio 2008)
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnMod.PerformClick();
}
}
Are you sure the click on the button isn't performed ? I just did a test, it works fine for me. And here's the way to prevent the "ding" sound :
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnMod.PerformClick();
e.SuppressKeyPress = true;
}
}
A few thoughts:
does the form have an accept-button (set on the Form) that might be stealing ret
does the textbox have validation enabled and it failing? try turning that off
does something have key-preview enabled?
Under "Properties" of the Form. Category (Misc) has the following options:
AcceptButton, CancelButton, KeyPreview, & ToolTip.
Setting the AcceptButton to the button you want to have clicked when you press the Enter key should do the trick.
Set e.Handled to true immediately after the line btnMod.PerformClick();.
Hope this helps.
I had to combine Thomas' answer and Marc's. I did have an AcceptButton set on the form so I had to do all of this:
private void tbxMod_Enter(object sender, EventArgs e)
{
AcceptButton = null;
}
private void tbxMod_Leave(object sender, EventArgs e)
{
AcceptButton = buttonOK;
}
private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Click your button here or whatever
e.Handled = true;
}
}
I used t0mm13b's e.Handled, though Thomas' e.SuppressKeyPress seems to work as well. I'm not sure what the difference might be.
form properties > set KeyPreview to true
The simple code below works just fine (hitting the Enter key while in textBoxPlatypusNumber displays "UpdatePlatypusGrid() entered"); the form's KeyPreview is set to false:
private void textBoxPlatypusNumber_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter)
{
UpdatePlatypusGrid();
}
}
private void UpdatePlatypusGrid()
{
MessageBox.Show("UpdatePlatypusGrid() entered");
}

Categories