How to do my "Button_click" when I press some key on keyboard? My code:
private void Button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
textBox1.Text = textBox1.Text + b.Text;
}
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
Char ch0 = '0';
if (e.KeyChar == ch0)
{
//MyButtonClick event
}
}
...
KeyPress event runs only when the button on form in focus, but I need to KeyPress worked just as I push the button on my keyboard. Please, give an exaple in you'r answer.
And don't be strict, I am only a beginner...
It is not completely clear that what are you asking, but I guess you want to do the same action on both keypress of your keyboard and when user clicks on the button.
look at this topic on MSDN for key_press:
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
MessageBox.Show("Form.KeyPress: '" +
e.KeyChar.ToString() + "' pressed.");
switch (e.KeyChar)
{
case (char)49:
case (char)52:
case (char)55:
MessageBox.Show("Form.KeyPress: '" +
e.KeyChar.ToString() + "' consumed.");
e.Handled = true;
break;
}
}
}
To do the same action in 2 event, you can write another method and call them from both events.
public void MyAction(mypars)
{
....
}
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MyAction(mypars);
}
private void Button_Click(object sender, EventArgs e)
{
MyAction(mypars);
}
It is also possible to call another event method, since they are like other methods, but I really do not suggest that! but it is like this:
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
Button_Click(sender,new EventArgs());
}
Update
You have to be better than "I want my button to be pressed". If you mean the visuals, you can set the focus of the control, like:
myButton.Focus();
Hope I could help you out :)
update 2
you have to use it like this
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
MyAction(mypars);
myButton.Focus();
}
if you need it to focus only on special chars, then check it before doing anythig like
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
MyAction(mypars);
myButton.Focus();
}
}
Related
In my C# Windows Forms application I want to navigate between two dateTimePicker (dateTimePicker1, dateTimePicker2) by pressing the Enter key.
When the Form open focus on dateTimePicker1 and press Enter key then focus dateTimePicker2 and press Enter key focus dateTimePicker1.
I'm trying the below code but it doesn't work:
private void dateTimePicker2_Enter(object sender, EventArgs e)
{
dateTimePicker1.Focus();
}
The Enter Event is triggered when you enter a control by pressing tab to change focus or clicking into it. If you want to listen for the enter key you need to use the KeyDown Event.
An implementation of the event handling would look like this:
private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
dateTimePicker2.Focus();
}
}
private void dateTimePicker2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
dateTimePicker1.Focus();
}
}
Try this
private void dateTimePicker1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
dateTimePicker2.Focus();
}
}
private void dateTimePicker2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
dateTimePicker1.Focus();
}
}
The Enter event does not represent the key press of the Enter key, it represents the user changing focus to the control.
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.enter(v=vs.110).aspx
You should use KeyDown event
private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
dateTimePicker2.Focus();
}
I want to make a TextBox that doesn't allow entering spaces. I disabled typing spaces with the keyboard:
void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Space)
{
e.Handled = true;
}
}
But if the user copies a string with spaces like "Hello world", he can paste it into the TextBox and there will be spaces in it.
you can add a TextChanged Event Handler for your TextBox and add below code in that TextChanged event:
TextBox1.Text = TextBox1.Text.Replace(" ", "");
A better control approach
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) {
removeSpaces();
}
//Handle Ctrl+Ins
if (e.KeyCode == Keys.Control && e.KeyCode == Keys.Insert)
{
removeSpaces();
}
}
private void removeSpaces()
{
textBox.Text = textBox.Text.Replace(" ", string.Empty);
}
// To control Mouse Right click
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
textBox1.ContextMenu = new ContextMenu();
}
}
SIMPLE Solution for all
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Replace(" ", string.Empty);
}
A simple way is removing white space after entering data. Like:
txt_Box.Text = txt_Box.Text.Replace(" ","");
Hi I'm new in C# visual programming and I'm facing a problem in winform that is I want to make the textBox accepts numbers only when a checkBox is checked ... the problem is that I know how to use the code inside KeyPress event but it doesn't work with the idea of checkBox.
I have this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsLetter(e.Keychar))
{
e.Handled = true;
}
}
Now the question is how to make this happens when a checkBox is checked???
on your key press event you could do:
if (this.checkBoxNumericOnly.Checked)
{
//your code to only allow numerics...
}
Thanks to all of you ..
I wrote this code to enter numbers but only one dot '.' and it works finally ... thanks a lot for help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.checkBox1.Checked)
{
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
}
Use the MaskedTextBox control and handle the checkbox event to change the mask property
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if(checkBox1.Checked == true)
{
maskedTextBox1.Mask = "000-000-0000";
}
else
{
maskedTextBox1.Mask = null;
}
}
Simply try this in your TextBox's keypress event :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(this.checkBox1.Checked)
{
//Allow only number
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
I am trying to disable people from deleting a textbox in a richtextbox. The project is using windows form.
Here is the code I have:
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.KeyPress += new KeyPressEventHandler(richTextBox1_KeyPress);
}
void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)8)
{
e.Handled = true;
MessageBox.Show("Try not to delete... write freely and openly");
//The msgbox shows, but the delete still happens within the form.
}
}
Does not show messagebox and does not stop the delete:
private void Form1_Load(object sender, EventArgs e)
{
richTextBox1.KeyDown += new KeyEventHandler(richTextBox1_KeyDown);
}
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
e.Handled = true;
MessageBox.Show("Delete Pressed");
// Does not show message box...
}
}
Per the MSDN documentation on KeyPressEventArgs.KeyChar, you cannot get or set the DELETE key using that event. You will need to use the KeyEventArgs.KeyCode instead, subscribing to the KeyDown and KeyUp events.
My solution:
void richTextBox1_TextChanged(object sender, EventArgs e) {
richTextBox1.SelectAll();
richTextBox1.SelectionProtected = true;
richTextBox1.Select(richTextBox1.Text.Length, 0);
}
Side note: yes, this will flicker. Proof of concept only. To avoid the flicker, see How to append text to RichTextBox without scrolling and losing selection?
Instead Of KeyPress event use KeyDown In RichText Box.
try this to prevent from deleting text in RichText Box
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 46)
e.Handled = true;
}
If you want to disallow both delete and backspace You Can Change KeyDown Event as follows
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 8 || e.KeyValue == 46)
e.Handled = true;
}
You must add Back key to prevent delete :
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
e.Handled = true;
MessageBox.Show("Delete Pressed");
// Does not show message box...
}
}
Edit:
Non-selectable RichTextBox :
public class ViewOnlyRichTextBox : System.Windows.Forms.RichTextBox {
// constants for the message sending
const int WM_SETFOCUS = 0x0007;
const int WM_KILLFOCUS = 0x0008;
protected override void WndProc(ref Message m) {
if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;
base.WndProc (ref m);
}
}
My solution is some kind of the combination of SerkanOzvatan's and LarsTech's answers. Here is the code:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete)
{
e.Handled = true;
MessageBox.Show("Try not to delete... write freely and openly");
// Does not show message box...
}
}
private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
richTextBox1.SelectionProtected = richTextBox1.SelectionLength > 0;
}
It works great :)
And here is another solution of my own which also works great, especially if you want to do with a TextBox (not a RichTextBox), it doesn't have a SelectionProtected, and this is used OK for both TextBox and RichTextBox (just change the class name in the following code accordingly):
public class WritableRichTextBox : RichTextBox
{
protected override bool ProcessKeyMessage(ref Message m)
{
int virtualKey = m.WParam.ToInt32();
if (SelectionLength > 0 || virtualKey == 0x08 || virtualKey == 0x2e)
{
if (virtualKey != 0x25 && virtualKey != 0x26 && virtualKey != 0x27 && virtualKey != 0x28)
return true;
}
return base.ProcessKeyMessage(ref m);
}
}
i already have code when user press key Enter on keyboard, it return tab and "jump" to next field, its working great, its possible make it for 2 or 3 textbox, problem when need make it on multiple textbox like 20 textbox for each form, its just not work.
See code:
// Detect if Enter key is pressed on each text box, mute sound enter "ding" sound and replace Enter for tab (problem that have make it for each textbox)
private void txtAltura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtLargura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtProfundidade_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
//execute keypress command when enter is typed on textbox
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
if (txtProfundidade.Text != "") { foreach (char c in txtProfundidade.Text.ToCharArray()) txtProfundidade_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
if (txtLargura.Text != "") { foreach (char c in txtLargura.Text.ToCharArray()) txtLargura_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtAltura_TextChanged(object sender, EventArgs e)
{
if (txtAltura.Text != ""){foreach (char c in txtAltura.Text.ToCharArray()) txtAltura_KeyPress(sender, new KeyPressEventArgs(c));}
}
Hope make it better.
Thanks in advance..
if its windows form app can use this, this will replace tab key press with Enter key
protected override bool ProcessKeyPreview(ref Message m)
{
if (m.Msg == 0x0100 && (int)m.WParam == 13)
{
this.ProcessTabKey(true);
}
return base.ProcessKeyPreview(ref m);
}
From what I understand, you're trying to figure out a way to assign event handlers to multiple textbox controls and don't want to write a handler for each one. If that's the case, try this:
private void Form1_Load(object sender, EventArgs e)
{
foreach (TextBox textBox in this.Controls.OfType<TextBox>())
{
textBox.KeyDown += new KeyEventHandler(textBox_KeyDown);
}
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
This will assign a handler to each textbox control on the form.
That worked perfectly well.
I also have to repeat this on each textbox to check if all codes was filled and update statusbar:
private void txtAltura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
Its possible to make it better ?