keydown to correspond with button down - c#

Hello I am trying to match the button down visual (on the WinForm, the button boarder gets a little darker, indicating it is pressed) with a keydown event. First of all I need to detect a keydown for numbers only. Then when the key goes down, the corresponding number button on the form should look like it is depressed as well. Sorry if this is already been answered using differt jargon. I already know how to perform a button click with the keydown.

Make a test code on KeyDown event. Write down the keyboard codes you shall see from pressing 0 to 9. Then use those keyboard codes in your KeyDown's if statement

You can use a Checkbox and set the appearance to be Button. Then you can do something like this:
private void OnKeyDown(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = true;
}
private void OnKeyUp(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = false;
}
As far as the Keys, you can just use the KeyEventArgs.KeyCode
e.KeyCode == Keys.D0 || .. || e.KeyCode == Keys.D9

Related

keydown event with keys.Enter and keys.Tag

I'm using some richTextBoxes in one page of my form, in keyDown of richTextBoxes, i wrote if Ctrl+Enter is pressed, sendKeys the Tab key so the next one get focus, and I also have a keyDown event on whole form, so when user press Ctrl+Tab, selected page change to next page
problem is, when i press Ctrl+Enter on the richTextBoxes, keyDown of form with Ctrl+Tab happens and tab changes, why it sees enter and tab alike ?
Sorry for my bad grammar, and thanks for your effort
keyDown event of Main Form:
private void Main_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Control)
{
//code for changing the tabs
}
}
keyDown event of richTextBoxes:
private void txtControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
{
SendKeys.Send("{Tab}");
e.Handled = true;
e.SuppressKeyPress = true;
}
}
Usually, when you press a key, the focused control receives the key pressed. You could change a bit of this flow setting the Form.KeyPreview property to True. With this setting the Form receives the key pressed before the focused control.
You are messing with this 'normal' flow trying to insert a fake TAB key while you are processing the KeyDown event that has reached the RichTextBox keydown event handler. You suppress the CTRL+ENTER key but, at the exit of the event, the TAB key is received by the form with the Control bit still set and, as far as I know, there is no easy way to reset this bit, hence you process a CTRL+TAB in your form keydown.
Fortunately all of this is not needed, you set the next control in tab order line simply with
private void txtControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Enter)
{
Control current = sender as Control;
this.SelectNextControl(current, true, true, true, true);
e.SuppressKeyPress = true;
}
}
The call to the form method SelectNextControl gives you a lot more control on what should happen and doesn't insert a fake TAB key in the keyboard processing.
You send tab SendKeys.Send("{Tab}"); on keydown. The modifier is stil CTRL. Than the keydown of the MainForm in focus catches Tab. Stop sending SendKeys.Send("{Tab}");?

How to make keyboard shortcuts to button click

I am doing my graduation work and I need a little help.
So far I've done most of my work and now I need someone to help me with the shortcuts.
This is how my work looks like (for now):
I need to make shortcuts for those buttons so that user doesn't have to click on button with mouse. I wish to make it possible that when user presses F1 on the keybord - it's like he pressed button1 with mouse. F2 stands for button2 and so on.
Shortcuts as CTRL+ some key are also acceptable. I only need example how to make couple buttons, and i will make others :)
Thanks
Set Form1's KeyPreview-property to true in the designer or in the code:
this.KeyPreview = true;
Then add KeyUp-action to your form, which accepts all keys (even Delete etc):
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
button1ClickMethod();
}
}
Then separate your buttons' actions to individual methods, like button1ClickMethod(), and avoid using the Button1_Click(null, null);. Call this button1ClickMethod() in the KeyUp-event when a desired key is up.
To use combinations, you can use this:
// If CTRL and F1 were pressed
if (e.Control && e.KeyCode == Keys.F1)
{
MessageBox.Show("Shortcut CTRL + F1 was pressed!");
}
You can also check if the Shift was pressed at the same time with e.Shift-property, same way like the e.Control.
KeyPress event will help you
Sample code ;
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
//Call the event according to key
// if(e.KeyChar == "")
//btnSave_Click(null,null)
}

TextBox.Keypress doesn't respond to return key

I have a form with various text boxes. One text box is used for entering a floating point number, so I am using TextBox.KeyPress to process each digit in turn, which only modifies the Text property. The text is processed by a routine that is called when the OK button id pressed (before closing the form). It is also called by the TextBox.Leave event. However, if I change the contents of the text box then press Return to variable isn't updated.
I thought I could overcome this by the following:
private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
prvUpdateDestPointNo();
}
}
This is called whenever a key is pressed while the text box is in focus, as can be proved by setting a breakpoint within it. However, it is not called when Return is pressed.
Can someone explain how I can ensure new text is processed when Return is pressed?
If I change the contents of one then click the OK button the new
I would use the Debugger to determine the value of e.KeyCode at runtime.
Why?
When I ran similar code (Winforms TextBox, KeyDown registered), the value of e.KeyCode was
e.KeyCode = LButton | MButton | Back
Another property of KeyEventArgs you can use is KeyValue -
private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13)
{
prvUpdateDestPointNo();
}
}
If you are using Windows Form Application, then you can set the AcceptButton property of the Form to the OK button and the Click event of the OK button will be fired when you press Enter/Return key

c# Listbox control (arrows and enter keys)

I have a listbox which displays the contents of an array. The array is populated with a list of results when my "go" button is pressed.
The go button is set as the AcceptButton on the form properties so pressing the Enter key anywhere in the focus of the form re-runs the go button process.
Double clicking on a result from the array within the listbox works fine using below:
void ListBox1_DoubleClick(object sender, EventArgs e) {}
I would like to be able to use my arrow keys and enter keys to select and run an event without having to double click on the line within the listbox. (however go button runs each time instead)
Basically open the form, type search string, press enter to run go button, use up and down arrows then press enter on selection to run same event as double click above. Will need to change focus after each bit.
You can handle the KeyDown events for the controls you want to override. For example,
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//execute go button method
GoButtonMethod();
//or if it's an event handler (should be a method)
GoButton_Click(null,null);
}
}
That will perform the search. You can then focus your listbox
myListBox.Focus();
//you might need to select one value to allow arrow keys
myListBox.SelectedIndex = 0;
You can handle the Enter button in the ListBox the same way as the TextBox above and call the DoubleClick event.
This problem is similar to -
Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox
Certain controls do not recognize some keys when they are pressed in Control::KeyDown event. For e.g. list box does not recognize if the key pressed is Enter key.
See the remarks section of the Control::KeyDown event reference.
One way to resolve your problem might be writing a method for the Control::PreviewKeyDown event for your list box control:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && this.listBox1.SelectedIndex - 1 > -1)
{
//listBox1.SelectedIndex--;
}
if (e.KeyCode == Keys.Down && this.listBox1.SelectedIndex + 1 < this.listBox1.Items.Count)
{
//listBox1.SelectedIndex++;
}
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}

Detect Key in KeyUp event

I have a textbox on a form where I'm trying to detect the keys the user types in. The TextBox is multilined with wordwrap on. I don't want the user the press the enter key (as I want all text entered on ONE line, wrapped) so I used the following code:
private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char)13) {
MessageBox.Show("Enter keys are not allowed");
e.KeyChar = (char)0;
}
}
This worked fine in my tests, but when I tested for CTRL+ENTER it didn't work as I'm not sure how to detect for the control key. From my googling I found that I need to use the KeyUp/Down events so I now have the following Code:
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
}
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
The problem with the KeyUp/Down event is that I don't know how to REMOVE the enter key from the text - unlike the KeyPress event when I can set the KeyChar to zero. The event captures both the Enter and Ctrl+Enter keys, but the cursor still goes to the next line in the TextBox.
Thanks for any help on this.
Hmm, there's no reason to disallow the Enter key by handling the KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the textbox control to False. This will prevent a multiline textbox from responding to a press of the Enter key.
Of course, this doesn't solve the problem of Ctrl+Enter. In fact, that's the expected way to create a new line when the AcceptsReturn property is set to False. To solve that, you will need to handle one of the keyboard events and prevent the control from receiving this input.
KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. That will catch them no matter which other modifier key they might be combined with. Then, once you've found an Enter keypress, you want to set the e.Handled property to True in order to prevent it from being passed on to the control.
But unfortunately, we're not quite done yet. The textbox control tries to handle certain keys internally, and you're not going to be able to override that in a key event handler method. You also need to tell the control not to interpret that particular key as an input key. There are two primary ways of doing this. The first (and recommended way) is to inherit from the base TextBox class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is just to handle the PreviewKeyDown event, and set the IsInputKey property to False.
Sample code:
private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Set the IsInputKey property to False
e.IsInputKey = false;
}
}
private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Show the user a message
MessageBox.Show("Enter keys are not allowed in this textbox.");
// Prevent the key event from being passed on to the control
e.Handled = true;
}
}
And, though I assume this is for testing purposes only, you definitely want to take that MessageBox call out of there for production code. Find another way to alert the user that their input was not allowed, such as a short beep sound and an ErrorProvider component placed next to the textbox. Showing a message box is very jarring, and not very user-friendly. See my answer here for other hints and tips.
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
// mark event as handled
e.Handled = true;
}
}
from msdnlink
edit:
I think that you need the key down event not the key up
EDIT2
here is some tested code and it works as you wanted:
bool invalid=false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
invalid = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (invalid)
{
e.Handled = true;
}
invalid = false;
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
You wanted to detect Ctrl + Enter.
if (e.KeyData == (Keys.Control | Keys.Enter)) {..
Keys.Control and Key.Enter are nothing but are some values please refer . Now doing logical or will not necessarily result to key which has been pressed. Totally illogical clause.
Ok now come to your actual problem you want to detect Enter stroke and Ctrl + Enter stroke to be treated as same.
Besides you want to undo the newline character thats been introduced. Try
PreviewKeyDown or Preview key up eventhandler with the following condition
if(e.KeyCode==Keys.Enter)
Let me know if this works

Categories

Resources