Do not handle button click when caused by key press - c#

I have a WPF project. In this project at some point I'm dynamically making button in code behind like this:
private Button makeButton()
{
Button b = new Button();
b.Width = 24;
b.Height = 19;
b.Click += ButtonClick;
return b;
}
Where the ButtonClick is:
public void ButtonClick(object sender, RoutedEventArgs e)
{
// Do stuff...
}
Sometimes happen the event handler is called on pressing enter, even when button is not focused.
So my question is how can I disable to handle this event when it's caused by enter.
Tnaks you

I had the same problem. Using PreviewMouseLeftButtonUp event fixed my problem. It will not hire when you use enter button

It is probably getting focused before you press Enter.
Anyway, you could try to set the Focusable property to false:
b.Focusable = false;
Also make sure that you don't set the IsDefault property to true.

I'm not sure how this is happening with the button not focussed. Maybe this is logical rather than keyboard focus.
It'd have been nice to have a minimal reproduction.
Two things you can try.
1)
Eat the enter key just in case the keypress is somehow going to the button by using the previewkeydown event on the button. Marking the event as handled will stop the keydown event from firing so no enter will reach the button if it's somehow logically receiving the keypress.
b.PreviewKeyDown += (o, e) =>
{
if (e.Key == Key.Enter) e.Handled = true;
};
Set IsDefault="False" on the buttons in case they're somehow being set as default.

Related

using Function Keys on a windows form

The requirement is for a user to enter a number in a textbox and if they press F5 the code does something with the value in the textbox. I have set the form's this.KeyPreview = true; When user hits F5 the keyup event fires and processes correctly, BUT now every time I enter a character in the textbox the keyup event also fires. Is there a way to turn this off? or is it just something I have to deal with in debugging? If I don't have breakpoint there it's fine, but do I want that event to fire for every character?
Subscribe to the textbox event Keyup
In the event handler check the KeyCode. If it equals Keys.F5 do what you want to do when F5 is pressed. Also inform the system that you handled the event. In all other cases do what you want to do if F5 is not pressed.
private void OnKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5)
{
this.HandleF5();
e.Handled = true;
}
else
{
// not F5
...
}
}
private void HandleF5()
{
// On F5 clear the textbox and sound a beep
this.textBox1.Text = String.Empty;
System.Media.SystemSounds.Beep.Play();
}
Consider to also check properties Alt and Control if you want to do simething different on Alt-F5 / Ctrl-F5.

Problems with Combobox MouseDown Events

I have two Problems with the Mouse Events of ComboBoxes. What I want to achieve is a "Touch-and-Release"-Solution, that means after the User pressed/touched the Combobox for 500ms something should happen. I have Class where I fireup all my Events to my Controls. For the Comboboxs I do it like this:
((ComboBox)obj).PreviewMouseDown -= CTRLMouseButtonEventHandler_Down;
((ComboBox)obj).PreviewMouseDown += CTRLMouseButtonEventHandler_Down;
((ComboBox)obj).PreviewMouseUp -= CTRLMouseButtonEventHandler_Up;
((ComboBox)obj).PreviewMouseUp += CTRLMouseButtonEventHandler_Up;
My Up/Down-Events look like this:
private void CTRLMouseButtonEventHandler_Down(object sender, MouseEventArgs e)
{
_currentControl = (Control)sender;
_touchHoldTimer = new System.Windows.Threading.DispatcherTimer();
_touchHoldTimer.Interval = TimeSpan.FromMilliseconds(500);
_touchHoldTimer.Tick += TouchHoldTimer_Tick;
_touchHoldTimer.Start();
}
private void CTRLMouseButtonEventHandler_Up(object sender, MouseEventArgs e)
{
_touchHoldTimer.Stop();
}
The first Problem is, when my Focus is on another Control and click into the Combobox and hold, nothing happens. I first have to click into the Combobox and then click-and-hold and it works.
My second Problem is, that the PreviewMouseDown is also fired when the Scrollbar or ToggleButton of the Combobox is pressed. I tried something like this:
((ComboBox)obj).AddHandler(TextBox.PreviewMouseDownEvent, new RoutedEventHandler(CTRLMouseButtonEventHandler_Down2));
((ComboBox)obj).AddHandler(TextBox.PreviewMouseUpEvent, new RoutedEventHandler(CTRLMouseButtonEventHandler_Up2));
But it didn' work. Can somebody point me in the reight direction please?
Add another event. Set Event for hovering mouse over Combobox to give it selection. It would be same as clicking on it.
EDIT:
other possible events:
DropDownOpened
ContextMenuOpening
https://msdn.microsoft.com/en-us/library/system.windows.controls.combobox_events(v=vs.110).aspx
2.
KeyDown event is not firing when pressing enter in an UserControl
Just replace enter with space.

Button KeyPress Not Working for Enter Key

I have a button for which I set the KeyPress event.
this.myButton.KeyPress += new KeyPressEventHandler(this.myButtonEvent_keypress);
private void myButtonEvent_keypress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return || e.KeyChar == (char)Keys.Space)
{
// do something
}
}
Now whenever the Space key is pressed, I get the event triggered. This part works fine.
But for some reason, the Enter key press is not triggering the KeyPress
event. Also Alt, Ctrl, Shift are not working.
How can I make the button receive Enter key press?
UPDATE:
I tried below too without any luck
this.myButton.MouseClick += new MouseEventHandler(myButton_Click);
When a Button has focus and you press Enter or Space the Click event raises.
So to handle Enter or Space it's enough to handle Click event and put the logic you need there.
So you just need to use button1.Click += button1_Click;
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
}
If you really want to know if Enter or Space was pressed, you can hanlde PreviewKeyDown event:
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if(e.KeyCode== Keys.Enter)
{
MessageBox.Show("Enter");
}
if (e.KeyCode == Keys.Space)
{
MessageBox.Show("Space");
}
}
Enter and space can be handled using click event.
this.myButton.Click += new EventHandler(myButton_Click);
The Button control in WinForms will eat Enter, Space, Tab, ESC, and a few other special key's press events. One method to intercept these events is to override Control.ProcessDialogKey. Or you can override IsDialogKey to say if a key should be handled as a special case.
A another option is to set KeyPreview = true on you parent Form. Then you can handle all KeyPress events at the Form level and use Form.ActiveControl if you need to see what control has Focus

C#: Form receives all keypresses except the ENTER key

I am designing a custom calculator. Any key pressed on this calculator form should be captured at the 'Form' level. To this end, I've the following code-
private void BindControlMouseClicks(Control con)
{
con.MouseClick += delegate(object sender, MouseEventArgs e)
{
TriggerMouseClicked(sender, e);
};
// bind to controls already added
foreach (Control i in con.Controls)
{
BindControlMouseClicks(i);
}
// bind to controls added in the future
con.ControlAdded += delegate(object sender, ControlEventArgs e)
{
BindControlMouseClicks(e.Control);
};
}
private void TriggerMouseClicked(object sender, MouseEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
this.KeyPress +=new KeyPressEventHandler(Form1_KeyPress);
BindControlMouseClicks(this);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
}
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
string key;
switch (e.KeyChar)
{
case '\r':
key = "ENTER";
break;
case ' ':
key = "SPACE";
break;
case (char)27:
key = "ESCAPE";
break;
default:
key = e.KeyChar.ToString();
break;
}
/* Some other code */
}
I've set breakpoints and added debug statements in the event handler function Form1_Keypress. Surprisingly all relevant keys ( Numerals, alphabets, Escape, Space etc ) hit the callback function except the ENTER key. This happens with the NUMPAD ENTER key too.
Any ideas why only the ENTER key is being handled differently?
EDIT
My form has a bunch of buttons and a textbox. When I place the focus on the textbox, voila, the callback is called for the ENTER key too! But if I put the focus on any of the buttons, no event is generated on ENTER key press. As I've set KeyPreview to true, the form must be getting this event irrespective of where the focus is, right?
EDIT 2
This happens only when there are buttons on the form and at least on of them has focus on it. If any other control has focus on it, it works just fine. I have not set AcceptButton attribute of the form.
As MSDN says(.NET TextBox - Handling the Enter Key), you can try use (char)Keys.Return instead of \r:
switch (e.KeyChar)
{
case (char)Keys.Return:
key = "ENTER";
break;
Also may be there is some button with AcceptsReturn property set to true on the form?
The problem I describe arises when any of the buttons on my form has focus. So I did these two things -
Set any_button.TabStop = false initially. This makes sure none of the buttons get focus when the form is launched
When we click a button with a mouse, it regains focus. And we end up in the same problem. To solve this, in the Mouse Click Handler, I just pass the focus from the button to some other control. For instance, my form had a menustrip and I just invoked, menustrip1.Focus() in the Mouse Click Handler.
Now, ENTER keypresses are caught in Form_Keypress handler.
This is a workaround. But I am yet to figure out why ENTER keypress is not caught by the form when the focus is on a button and not on other controls. I would be glad to have more answers for this Qn

Set focus to element

There are a button and a textbox. I added a "KeyDown" event to textbox so that when "enter" is pressed button gets clicked. Good, then I tried to give focus to textbox again but failed. In the code below I tried three ways but neither is working.
private void txt_addRemove_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
btn_BC_add.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
// 1.way
// IInputElement focusedElement = FocusManager.GetFocusedElement(txt_addRemove);
// 2.way
// Keyboard.Focus(txt_addRemove);
// 3.way
// txt_addRemove.Focus();
}
}
Add this
if (!textBox1.Focus())
{
textBox1.Focus();
}
What this does:
1. We check if the textbox is NOT focused.
2. If it is not focused, focus the control.
EDIT: How about this:
btn_BC_add.PerformClick()
Try focusing the textbox after the event handler is finished using:
Dispatcher.Invoke(() => { txt_addRemove.Focus(); })
couldnt you also try changing the focus from the button event handler? this might not be desirable if you dont want the focus to be on your textbox after a normal click of the button, but it should work.
Im guessing that your button click is generating a post back before the focus can be changed

Categories

Resources