KeyDown and keyUp event to avoid repeat letter in textbox control - c#

My question is:
How can I disable the hold a key down in a textbox control using C#?
e.g Boxxxxxxxxxxxxxxxxxxxxx
I don't want to allow user to repeat any character from the keyboard.
Any suggestion?
thanks

Just an extra note for everyone using KeyDown and KeyUp events to suppress key repeat. If you do this you need to exclude catching meta keys like Alt/Shift etc otherwise when those keys are held down the actual key you want will not be sent since this is a two key combination and KeyDown and KeyUp events catch all keys.
This applies to all two-key combinations.
I did not add all of the meta keys to the following example, just the most common ones.
You can easily add your own keys by adding them to the collection.
Extending on the post from BFree:
public partial class Form1 : Form
{
private static readonly System.Collections.Generic.ICollection<System.Windows.Forms.Keys) ExcludeKeys = new System.Collections.Generic.HashSet<System.Windows.Forms.Keys)()
{
System.Windows.Forms.Keys.None,
System.Windows.Forms.Keys.Shift,
System.Windows.Forms.Keys.ShiftKey,
System.Windows.Forms.Keys.LShiftKey,
System.Windows.Forms.Keys.RShiftKey,
System.Windows.Forms.Keys.Alt,
System.Windows.Forms.Keys.Control,
System.Windows.Forms.Keys.ControlKey,
System.Windows.Forms.Keys.LControlKey,
System.Windows.Forms.Keys.RControlKey,
System.Windows.Forms.Keys.CapsLock,
System.Windows.Forms.Keys.NumLock,
System.Windows.Forms.Keys.LWin,
System.Windows.Forms.Keys.RWin
}
private bool isKeyPressed = false;
public Form1()
{
InitializeComponent();
this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
}
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!ExcludeKeys.Contains(e.KeyCode))
{
isKeyPressed = false;
}
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!ExcludeKeys.Contains(e.KeyCode))
{
e.SuppressKeyPress = isKeyPressed;
isKeyPressed = true;
}
}
}

You can use the SupressKeyPress property on KeyEventArgs:
public partial class Form1 : Form
{
private bool isKeyPressed = false;
public Form1()
{
InitializeComponent();
this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
}
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
isKeyPressed = false;
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = isKeyPressed;
isKeyPressed = true;
}
}

bool prevent = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = prevent;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
prevent = false;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
prevent = true;
}

I'm not familiar with the specifics in c# but I imagine something like:
while (keyIsDown){
//do nothing
}
would work. I would be surprised if there is no way to keep track of a key being pressed.

Related

How to disable a combobox on clicking on another combox list data in C sharp?

I want to design a windows form using C sharp on Visual Studio 2013.
I go through the Source from here. but did not got it properly.
for that I have 3 combobox. I want to disable combobox2 when I click on combobox1 NSSCM element and enable when click on NSSFO element.
Below is my part of code snippet:
namespace NSE_First_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MaximizeBox = false;
MinimizeBox = false;
if (true)
{
comboBox1.Items.Add(Exchange.NSSCM.ToString());
comboBox1.Items.Add(Exchange.NSSFO.ToString());
comboBox1.Items.Add(Exchange.BSSCM.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
string selectedItem = string.Empty;
ProcessValue(selectedItem);
}
public enum Exchange
{
NSSCM = 1,
NSSFO = 2,
BSSCM = 3
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
comboBox2.Enabled = false;
if (comboBox1.selectedIndex == 1)
comboBox2.Enabled = true;
}
Try this:
//This will disable combobox2 on the click of it
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox2.Enabled = false;
}
//This will enable combobox2 on the click of it
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox2.Enabled = true;
}
Because you want it on click, use the CLICK event, instead of SelectedIndexChange event.

Keyup not working on custom theme called "Net Seal Theme"

Today I'm having a problem with the keyup event not working on a custom theme.
public Main()
{
InitializeComponent();
tbResolveS2I.KeyUp += new KeyEventHandler(tbResolveS2I_KeyUp);
tbResolveI2S.KeyUp += new KeyEventHandler(tbResolveI2S_KeyUp);
this.KeyPreview = true;
}
private void tbResolveS2I_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnResolveS2I_Click(sender, e);
e.SuppressKeyPress = true;
}
}
When I hit enter on my keyboard it sends both textboxes to do the same result. What i mean is if i hit enter on the first textbox it will act like I'm pressing enter on the other textbox aswell
If you want different events to perform the same thing you could add that code to a method and just call that method from the controls event method.
Also in the theme pack you are using, the button extends from Control and does not have a PerformClick() method.
example:
public Main() {
InitializeComponent();
KeyUp += new KeyEventHandler(Main_KeyUp);
this.KeyPreview = true;
}
private void Main_KeyUp(object sender, KeyEventArgs e) {
if(e.KeyCode == Keys.Enter) {
CustomCode();
e.SuppressKeyPress = true;
}
}
private void btnResolveS2I_Click(object sender, EventArgs e) {
CustomCode();
}
private void CustomCode() {
//Perform code here
}
}

What to pass to Method that Checks if Key is Pressed?

Okay so I created a method called KeyCheck(), that should check if a key is pressed (specifically the enter key) and if it is it will press button1.
Unfortunately when I call the method I am unsure what to pass along to it. I want it to know when the enter key is being pressed.
public partial class Form1 : Form
{
public void GameStart()
{
richTextBox1.WordWrap = true;
richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
richTextBox1.Text = "Hello, Welcome to Grandar!";
}
public Form1()
{
InitializeComponent();
GameStart();
//What variable do I pass to KeyCheck Method?
KeyCheck();
}
private void KeyCheck(KeyPressEventArgs k)
{
if (k.KeyChar == (char)Keys.Enter)
{
button1.PerformClick();
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}
Couple of things to note here:
a) Do you really want to be calling KeyCheck directly as your sample code suggests or should it be wired up as a handler on the form (where the info you're asking will be automatically provided - will require a change in signature to align with the standard handlers as you have in some of your other methods).
b) I don't think you'll be able to call the KeyCheck method like you're doing unless you hook up another event to capture the keypress and then pass it to this method, by newing up a new KeyPressEvent(...)
Therefore, to answer your question, I think you'll want something like (pseudo-code)
public Form1()
{
InitializeComponent();
GameStart();
// Wire up a handler for the KeyPress event
this.KeyPress += KeyCheck;
}
private void KeyCheck(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
button1.PerformClick();
}
}
Check out this page: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx
You'll want something similar to your other methods, with the sender object and the event args.
if (e.KeyCode < Keys.Enter) {
//Your logic
}
subscribe to this:
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress_Method);
and the method to check the Enter key:
void KeyPress_Method(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key
{
// your code
}
}

how to do label.text = readKey in WFA

How can I ensure that when you click on label, application expect to press any key, and when user press key, label text change to this key char?
Ok, now i have:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool isLabelClicked = false;
private void label1_Click(object sender, EventArgs e)
{
isLabelClicked = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (isLabelClicked)
{
label1.Text = ((char)e.KeyValue).ToString();
isLabelClicked = false;
}
}
}
And if I press Up, Down, Left, Right, Tab or Enter, application not responding and still expects press key. Only when I press any other key, application works well.
If I create new project and paste the same code, all works well, for Up, Down, Left and Right also, but I need this keys for my application which I do.
This example a textBox class : when press any key show it
using System;
using System.Windows.Forms;
using System.Drawing;
namespace KeyPressDisplayTextBox {
public partial class Form1 : Form {
private TextBox textBox1;
private Label label1;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
textBox1 = new TextBox();
textBox1.Location = new Point(10,10);
textBox1.KeyPress += textBox1_KeyPress;
Controls.Add(textBox1);
label1 = new Label();
label1.Location = new Point(10, 40);
label1.BorderStyle = BorderStyle.FixedSingle;
label1.Font = new Font("Arial", 14);
Controls.Add(label1);
}
void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
label1.Text = e.KeyChar.ToString();
}
}
}
Best regards
You can handle KeyDown event on the Form and get the KeyValue as below
Try This:
You need to set the Form KeyPreview property to True to receive the key events from the Form
bool isLabelClicked = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (isLabelClicked)
{
label1.Text = ((char)e.KeyValue).ToString();
isLabelClicked = false;
}
}
private void label1_Click(object sender, EventArgs e)
{
isLabelClicked = true;
}

c# request FormClosing

I have a form to ask for some data. At leaving of an input field (TextBox, DGV) the appropriate _Validating methode or _CellValueChanged methode is called.
If I want to end the program this methode is called, too - before the _FormClosing methode is called.
How can I fin out whether the program branches into the _FormClosing methode or not?
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( [FormClosing is active] )
{
// Do something
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// ... and this but later
// Write the Logfile
}
How have I to replace [FormClosing is active] to get to the right result?
I tried so
if ( this.FormClosing== true )
and so
this.FormClosing +=new FormClosingEventHandler(MyForm_FormClosing);
and so
FormClosingEventHandler cl = new FormClosingEventHandler(MyForm_FormClosing);
but I always was in a dead end.
This would do the trick:
public class YourForm : Form
{
private bool bIsClosing = false;
public YourClass()
{
InitializeComponent();
this.FormClosing +=
new FormClosingEventHandler(MyForm_FormClosing);
}
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( bIsClosing )
{
// Do something
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
bIsClosing = true;
// Write the Logfile
doLog("whatever");
}
}
this.FormClosing is an event that gets triggered once your form starts closing (like clicking the close button), hence the name. You need your application to register that event like so:
this.FormClosing +=new FormClosingEventHandler(MyForm_FormClosing);
This insures that once the FormClosing event gets triggered, your MyForm_FormClosing will be called.
You can create a flag like bool bIsFormClosing and set that flag once your closing function get called.
Edit:
As I understand now by reviewing your answer and your comments, you want to know in your doLog function if the form is closing.
Here is another approach
`
public class YourForm : Form
{
private bool bIsClosing = false;
Private bool bClosingHandled = false;
public YourClass()
{
InitializeComponent();
this.FormClosing +=
new FormClosingEventHandler(MyForm_FormClosing);
}
private void txb_Validating(object sender, CancelEventArgs e)
{
doLog("Text 1");
}
private void dgv_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
doLog("Text 2");
}
private void doLog(string txt)
{
// this is first called at closing...
if( bIsClosing )
{
// Do something
bClosingHandled = true;
this.close();
}
else
{
// Do someting different
}
}
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
If(!bClosingHandled)
{
bIsClosing = true;
e.Cancel = true;
return;
}
// Write the Logfile
doLog("whatever");
}
}`
This approach uses two flags... When you first receive a close event, you set the bIsClosing flag to true, cancels the event and return. Then once your dolog function get called, you force the close operation.

Categories

Resources