KeyEventArgs in C# - c#

I have a problem to how to catch which key is pressed. This is my code, but i cant get what key was pressed. I'm using KeyEventArgs for declaration of new variable and then comparing it.
private void textBox2_TextChanged(object sender, EventArgs e)
{
KeyEventArgs k = null;
if (e is KeyEventArgs)
{
k = (KeyEventArgs)e;
}
if (k.KeyCode == Keys.Enter)
{
// do something here
}
}

You need to add:
[component_name].KeyDown += new System.Windows.Forms.KeyEventHandler(this.Key_Pressed_Method);
into the constructor of your Form. Then, you can define what you want to do in Key_Pressed_Method() method.

TextChanged won't give you a KeyEventArgs. You want KeyUp, KeyDown or KeyPress instead. KeyPress gives you KeyPressEventArgs instead.

Related

C# Try to fire an event to call function

When I press enter, which enables the buttonEditClient_PressEnter function,
the buttonEditClient_ButtonClick function should be called.
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//fire buttonEditClient_ButtonClick function
}
}
private async void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
//buttonEditClient_ButtonClick activated
}
In the Designer:
this.buttonEditClient.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEditClient_ButtonClick);
this.buttonEditClient.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonEditClient_PressEnter);
If I try this:
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonEditClient_ButtonClick(sender, e)
}
}
I get this error:
cannot convert from 'System.Windows.Forms.KeyEventArgs' to 'DevExpress.XtraEditors.Controls.ButtonPressedEventArgs'
How can I activate the buttonEditClient_ButtonClick function?
A click event is inherently different from a keyboard event (e.g., one includes information about the pressed mouse button and cursor position, the other about the pressed key), so you can't pass your KeyEventArgs to the click handler, which expects a ButtonPressedEventArgs.
You have a few simple options here:
Move your code from the button click handler to an extra function, and call that from both your handlers.
Find a way to create a new ButtonPressedEventArgs instance inside the key handler, and then pass that instead of the KeyEventArgs. This would be a very slipshod solution, as you're literally making stuff up (what cursor position are you going to give it?).
The first solution could look something like this:
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonEditClientSubmit();
}
}
private async void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
buttonEditClientSubmit();
}
private void buttonEditClientSubmit()
{
// your code...
}
It depends on if you actually need anything from the ButtonPressedEventArgs. If you don't need anything from ButtonPressedEventArgs, you could just have both events call one function.
private void Handle_buttonEditClient()
{
// Do what you want to do when the button is pressed or has the "Enter"
// key pressed on it.
}
private void buttonEditClient_PressEnter(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Handle_buttonEditClient();
}
}
private void buttonEditClient_ButtonClick(object sender, ButtonPressedEventArgs e)
{
Handle_buttonEditClient();
}
Note
I made buttonEditClick_ButtonClick synchronous, but if you leave it async the same thing applies. Just have both events call the same function.
If you need the ButtonPressedEventArgs, then it's like Anas Alweish says. You'll have to create an instance of ButtonPressedEventArgs. I'm not familiar with DevExpress, so I don't know how you'd do that. Maybe something like new ButtonPressedEventArgs(buttonEditClient)?;
DevExpress Docs on ButtonPressedEventArgs

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)

Mask edit text box focus

I am using mask edit TextBox.The textbox always shows 0 (zero). I cannot type any key from the keyboard. I need to delete the zero first then I can type digits. Therefore I am doing extra steps here. Is it possible to type as soon as I type from the keyboard? Any suggestion is welcome.
private void DateDay_GotFocus(object sender, RoutedEventArgs e)
{
if (((TextBox)sender).Text == "Day")
((TextBox)sender).Text = string.Empty;
}
private void DateDay_LostFocus(object sender, RoutedEventArgs e)
{
if (((TextBox)sender).Text == string.Empty)
((TextBox)sender).Text = "Day";
else
CheckForCorrectDateDay((TextBox)sender);
}
I have tried with Focus event but not successful:
You need to select all content in the textbox in GotFocus event. For MaskedTextBox control it handle the selection internally after the focus event fire. So we need to do BeginInvoke to call the SelectAll() afterward.
private void DateDay_GotFocus(object sender, RoutedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate() {
((TextBox)sender).SelectAll();
});
}
This way you can start typing directly.
You can't make the text null if null is not allowed.
WPF version:
private void TextBox_GotFocus(object sender, RoutedEventArgs e) {
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() {
((TextBox)sender).SelectAll();
});
}
Alternate solution for MaskedTextBox using the Enter Event
private void maskedEdit_Enter(object sender, EventArgs e)
{
MaskedTextBox maskedTextBox = (MaskedTextBox)sender;
maskedTextBox.BeginInvoke
(new Action
(() =>
{
maskedTextBox.SelectAll();
}
)
);
}

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.

C# Textbox Keypress Control Help

I have a standard textbox that I want to perform an action on a keypress. I have this code currently:
private void idTextEdit_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter/Return)
{
e.Handled = true;
SearchButtonClick(sender, EventArgs.Empty);
}
}
The problem is, I have tried both Enter and Return up there which is the reason for that. It is only firing that check for normal keys that are not like shift, control, etc. How can I design this so that it will pick up and use the enter/return key in the same way?
You should use the KeyDown event instead:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
//...
}
}
If it for some reason has to be KeyPress, you can use (char)13 or '\r' for your check, though I doubt that would work well on a non-Windows OS.
if (e.KeyChar == '\r')
You cannot just cast Keys.Return to a char, because it's a bitflag enum and doesn't just hold the corresponding ASCII code.
Use the KeyDown event instead.

Categories