How to test Ctrl key up? - c#

I can't get the Ctrl key state in the KeyUp event handler as the Ctrl key is released.
Do I have to test the keycode of the event argument?
Is there any other way?

Wiring an event to the KeyUp event handler will work.
The following code will trigger when the Ctrl key is released:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey)
{
MessageBox.Show("Control key up");
}
}
If you want to test if the Ctrl was pressed in combination with another keystroke, for example: Ctrl+F1 then the following code snippet might apply:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.F1)
{
MessageBox.Show("Control + F1 key up");
}
}
Side note: You might have to enable KeyPreview on the form in order to catch all control KeyUp events in a single location.

private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if(e.Modifiers == Keys.Control)
...
}

Related

How do I make it so pressing Enter in a textbox does the same as clicking the button next to it?

I'm working on a C# based chat client in Windows Forms. I want to make it so a user won't always have to click the button when they want to send a message. Instead, hitting the Enter or Return key should be sufficient.
Here is a screnshot of my Form:
Handle KeyPress event for your textbox and code it like below in .cs page
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
MessageBox.Show("Your code here for enter key", "Enter Pressed");
}
}
You could create a Keydownevent for the textbox and ask for the enter key:
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1.PerformClick();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
You can use the KeyPress event of the TextBox to know which key is pressed. When the Return key is pressed, programmatically click the Senden button.
Event Handler:
private void CheckEnter(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
// Enter key pressed
}
}
And register the event like this (or use the visual editor):
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEnter);
Source
You can use your textbox keydown event to check whether you have pressed enter or not then call the submit button click event from there,
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonsSubmit_Click(this, new EventArgs());
}
}

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.

An error when trying to do key press event in C#

I add a key press event
private void listView_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
DeleteContact();
}
}
The framework automatically creates the class for it:
this.listView.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress);
When compiling I get an error on System.Windows.Forms.KeyPressEventHandler(this.listView_KeyPress)
No overload for 'listView_KeyPress' matches delegate 'System.Windows.Forms.KeyPressEventHandler' D:\...\MainForm.Designer.cs
I would appreciate any helpful answer, thanks.
The KeyPress event needs the parameter KeyPressEventArgs instead of KeyEventArgs.
However the KeyPress event only gives you the character of the key you pressed. And the DELETE key has no character. Therefor you should use the event KeyDown instead, as this one is gives you the KeyCode instead:
this.listView.KeyDown+= new System.Windows.Forms.KeyPressEventHandler(this.listView_KeyDown);
private void listView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
DeleteContact();
}
}
Your signature is wrong. The e parameter in your handler shoudl be KeyPressEventArgs not KeyEventArgs
The KeyPressEventHandler delegate expects the second parameter to be a KeyPressEventArgs object, not KeyEventArgs:
private void listView_KeyPress(object sender, KeyPressEventArgs e)
If you need to use information found in KeyEventArgs, you should instead use the KeyDown event. If so, be aware that the KeyDown event can be raised several times, if the user keeps the key pressed.
See
KeyPressEventHandler
private void listView_KeyPress(object sender, KeyEventArgs e)
has to be changed to
private void listView_KeyPress(object sender, KeyPressEventArgs e)

C# - How to override actions for "Up arrow" and "Down arrow" for a textbox?

I have a textbox and below it i have a listbox.
While the user is typing in the textbox if he presses the up or down arrow he should make a selection in the listbox. The textbox detects all the characters (except space) but it seems that it can't detect the arrow presses.
Any solution for this? This is a WPF project btw.
EDIT, Here's the working code thanks to T.Kiley:
private void searchBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
{
e.Handled = true;
//do your action here
}
if (e.IsDown && e.Key == Key.Up)
{
e.Handled = true;
//do another action here
}
}
I just tried this and it works. Add a preview key down event to the textbox
private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
MessageBox.Show("It works");
}
You can listen to they KeyDown event of the TextBox. In the handler, check whether the arrow key was pressed (you might need to listen to key up to avoid triggering your code multiple times if the user holds down the button for too long).
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
// Do some code...
}
}

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