WinForms ALT key beep - c#

I have an application in which I have implemented some keyboard shortcut keys for a given set of operations, some of these use ALT as a modifier e.g. ALT + 1. The functionality itself works fine however the system beeps during the key press.
I have read various posts that say I could use e.Handled in the KeyPress event however this is not helping in my scenario. The problem is easily replicated by creating a new Windows Forms application and running it without any modifications, pressing ALT + 1 for example will cause the system to beep.
I have noticed that other application such as Notepad have this behaviour too, if you launch Notepad and press ALT + J (or any other invalid menu keypress) the system will beep.
Is there any way to prevent the beep via my application or is it standard Windows behaviour?

You can Handle KeyDown Event and do something like this for Alt+1 But i suspect you might have to do this for all the invalid keys
private void keyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode >= Keys.D1 && e.Alt)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
}

Can you try to use SuppressKeyPress in you KeyPress event management?
e.SuppressKeyPress = true;

I use Alt+E for editing a record under certain circumstances.
Here's what I had to do to eliminate the beep.
private void Object_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.E && e.Alt)
{
e.SuppressKeyPress = true;
}
}
private void Object_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.E && e.Alt)
{
e.SuppressKeyPress = true;
EditRecord(); // This opens a form for the editing process
}
}
Note: If you try to use EditRecord from Object_KeyDown and only SuppressKeyPress in Object_KeyUp, you will still get the beep.

Related

How to make TextBox to receive only number key values using KeyDown Event in C#?

This code in my form updates the textBox1.Text twice whenever number keys are pressed.
private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
//MessageBox.Show();
if( char.IsNumber((char)e.KeyCode) ) {
textBox1.Text += (char)e.KeyCode;
}
}
Explain why if you can?
Modify the code or provide me a better solution for this.
Input ( in textbox1 ):
54321
Output:
1234554321
When you press a key, a character is already appended to your TextBox. Then you run the following code and, if the key represents a number, you append it again:
if (char.IsNumber((char)e.KeyCode)) {
textBox1.Text += (char)e.KeyCode;
}
If you want to suppress any key that's not a number, you could use this instead:
e.SuppressKeyPress = !char.IsNumber((char)e.KeyCode);
From the syntax I assume you are using WinForms for the following answer.
The key pressed event is not suppressed, so it still works like a normal key pressed event and adds the character to the text of the box. Additionally you add the character to the text yourself once again.
Try to suppress the key pressed event in case a key is pressed, you do not want to allow.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!char.IsNumber((char)e.KeyCode))
{
e.SuppressKeyPress = true;
}
}
You can try like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
}
Check New keyboard APIs: KeyEventArgs.SuppressKeyPress
The problem is that "Handled" doesn't take care of pending WM_CHAR
messages already built up in the message queue - so setting Handled =
true does not prevent a KeyPress from occurring.
In order not to break anyone who has currently got e.Handled =
true, we needed to add a new property called SuppressKeyChar. If we
went the other way, if "handling" a keydown suddenly started to
actually work, we might break folks who accidentally had this set to
true.
Try this code to accept numbers only
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
e.Handled = true;
}

How can I get my cursor out of the textbox?

I have a pretty complex visual studio form where I have like 2 textboxes, and some other stuff I need for my project, but my problem is - I want to use arrow keys to do tasks (bind them like short-cuts) and I can do that only when I don't edit my textboxes or else I get stuck in them and even if I try to reset my cursor (click on the form) it stays in the textbox and I can only jump in between characters, not use my arrows like I binded them. So my two questions are -
How can I reset my cursor if I have previously selected a textbox?
How can I unbind my default arrow keys so they don't jump between characters and buttons?
Try adding a key event on the textboxes that catches the arrow key strokes and moves focus accordingly.
void inputField_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right) || (e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Down))
{
//nextControl.Focus();
}
}
Just be aware that this will then remove the ability to navigate between the characters in a textbox. I think that the numpad arrows might still work inside the textbox since they have a different keycodes, but I can't be sure right now.
Hi and Welcome to stackoverflow, I'm not sure i have a complete answere but I have a few thougth on the subject.
Hard to answeer without some code, to se how you turns off the curser i think?
why does it have to in the first place? seems to overcomlicate it abit ?
the way i whould go about this, it's to egnore the the muse curser all together at first, and make a on KeyDown event on the textbox that needs the to be able to shift to the next like this
private void yourControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down || e.KeyData == Keys.Up)
{
// shift to next textbox maybe, to keep thing simple ?
}
}
though this will act wierd if you use a mulitlines textbox or other control that allready have these keys bind.
you can allso add a field boolean as a switch to enable the keys, that gets set on the textsboxes activation (thats what happens then you click it to write text) and it can be reused, then it look like this
class yourProgram
{
private bool fieldIskeysMode = false;
private void yourControl_KeyDown(object sender, KeyEventArgs e)
{
if (fieldIskeysMode) // if True
{
if (e.KeyData == Keys.Down || e.KeyData == Keys.Up)
{
// shift to next textbox maybe, to keep thing simple ?
}
if (e.KeyData == Keys.Escape) fieldIskeysMode = false; // one line set to falls on esc key
}
}
private void yourControl_Activate(object sender, KeyEventArgs e)
{
if (!fieldIskeysMode) // if not true
{
fieldIskeysMode = true;
}
}
}
hope this helps.

Are some keyboards more loquacious than others?

The lead developer says that when he uses my app, his keyboard beeps when he moves between TextBoxes on the TableLayoutPanel via the directional arrow keys.
However, I hear no such aural activity.
Here's my code:
// Had to intercept Up and Down arrows from Windows
private void textBoxPlatypi_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Up)) {
SetFocusOneRowUp(tb.Name);
return;
}
if (e.KeyCode.Equals(Keys.Down)) {
SetFocusOneRowDown(tb.Name);
return;
}
}
private void textBoxPlatypi_KeyDown(object sender, KeyEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Left)) {
SetFocusOneColumnBack(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Right)) {
SetFocusOneColumnForward(tb.Name);
e.Handled = true;
return;
}
}
..He thought maybe I needed "e.Handled" but that is not available in the PreviewKeyDown event.
Is there a way to suppress the beeping (which apparently occurs only with certain keyboards or specific setups (he's using Windows7, I'm on XP still))?
UPDATE
I've got this code now:
private void textBoxPlatypus1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
switch (e.KeyCode) {
case Keys.Down:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
private void textBoxPlatypus1_KeyDown(object sender, KeyEventArgs e) {
TextBox tb = (TextBox)sender;
if (e.KeyCode.Equals(Keys.Up)) {
SetFocusOneRowUp(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Down)) {
SetFocusOneRowDown(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Left)) {
SetFocusOneColumnBack(tb.Name);
e.Handled = true;
return;
}
if (e.KeyCode.Equals(Keys.Right)) {
SetFocusOneColumnForward(tb.Name);
e.Handled = true;
return;
}
}
...but he still hears the beeping (I don't).
He's in Alaska and using Windows 7; I'm in California and using XP. I don't know if some combination/mismatch there is the problem...
UPDATED AGAIN
I know this may be shocking to some, but the Alaska/California disconnection has nothing to do with it. I'm now hearing the beeps, too, and it's not from the arrow keys. It's when a value is entered in a TextBox and then, if that text box already has a character, focus is moved to the next textBox and the value is entered there (this is my code that causes this to happen). But the irritating beeping seems to be random - I haven't figured out the pattern for when it beeps (sometimes it does, sometimes it doesn't)...has anybody ever run across anything like that, or, better yet, know how to suppress the beep? All I'm doing is pressing either the "1" or the "2" key above the keyboard.
There is no way in the PreviewKeyDownEvent to Handle / Supress a KeyEvent like there is in the normal KeyDown Event. What the documentation suggests is to set the PreviewKeyDownEventArgs.IsInputKey property to true in order to handle key presses that are not available normally in the KeyDown Event.
From above Link, they are using a button as an example:
Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are typically ignored by some controls because they are not considered input key presses... By handling the PreviewKeyDown event for a Button and setting the IsInputKey property to true, you can raise the KeyDown event when the arrow keys are pressed. However, if you handle the arrow keys, the focus will no longer move to the previous or next control.
Try this:
e.SuppressKeyPress = true;

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

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