handling function key press - c#

I have a C# form with 5 buttons. The users enters the information and depending on the press of a function key, a specific action is performed. F9-Execute Order, F6-Save, F3-LookUp.
I have added the foolowing code:
OnForm_Load
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
and
private void KeyEvent(object sender, KeyEventArgs e) //Keyup Event
{
if (e.KeyCode == Keys.F9)
{
MessageBox.Show("Function F9");
}
if (e.KeyCode == Keys.F6)
{
MessageBox.Show("Function F6");
}
else
MessageBox.Show("No Function");
}
but nothing happens
Thanks

You need to set
KeyPreview=True
for your form. Otherwise key press is swallowed by the control that has focus.

Related

UWP problems in detecting the "Enter" key pressed

I'm trying to run some functions in my app when the Enter key is pressed on the keyboard, but I'm having problems in doing that.
KeyboardControl is in the KeyDown of my textbox.
Key.Enter is not recognized as a function, and I don't know what to do.
// When a key is pressed on the keyboard
private void KeyboardControl(object sender, KeyEventArgs e)
{
if (e.KeyStatus == Key.Enter)
{
PercentCalc();
PercentageValue.Text = Convert.ToString(result, new CultureInfo("en-US")) + "%";
}
}
Attach KeyDown event to your TexBox like this :
<TextBox KeyDown="Box_KeyDown" />
at the backend keydown event check if the pressed key is Enter and then execute your code in that if condition.
private async void Box_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{//execute code here
PercentCalc();
PercentageValue.Text = Convert.ToString(result, new CultureInfo("en-US")) + "%";
}
}
you were trying to check the KeyStatus which is not required in your usecase, instead you should be checking which key is pressed.

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

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

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

Form KeyUp and KeyDown events to change variables

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.

Categories