Problems with KeyPressEventArgs - c#

here's my problem .. i'm doing a calculator in C# and i don't want to click every single button to make a operation, i wanna handle it with my num pad .. like
if i press "1" , show me in the textbox "1".
i changed
private void cmd1_Click(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1')
{
txtShow.Text='1';
}
}
and i'm having this error :
No overload for 'cmd1_Click' matches delegate "System.EventHandler"
this.cmd1.Click += new System.EventHandler(this.cmd1_Click);
what the hack is wrong with this?
Cheers.

change
this.cmd1.Click += new System.EventHandler(this.cmd1_Click);
to
this.cmd1.KeyPress += new System.EventHandler(this.cmd1_Click);
You'll probably want to rename cmd1_Click too.
And as mentioned in the answer above, this would be better on the Form itself, rather than each button.

You are trying to attach an event handler that corresponds to a KeyPress event to a Click event.
There is something wrong here (bad copy/paste?):
private void cmd1_Click(object sender, KeyPressEventArgs e)
It's named as an auto-generated event handler for the Click event on cmd1, but its definition is the definition for a KeyPress event handler.
Which event do you want to handle? KeyPress or Click or both?

Click is a mouse event, you need to attach to a keyboard event if you want to receive keyboard event args, you'd have to put all your calculator buttons in a common pannel and handle both the button click "and" the text being sent to the panel, that way you could react to both keypresses anywhere and to click for the same result.
An easy way to handling events for all the buttons without doing it one by one is to have a single button click handler and check the text property of the control to know how to act (cast the sender to a button and check the text, do a switch on that)
Not tested:
switch(((button)sender).Text)
{
case "1":
// react to user having pressed 1 etc etc
}

Related

Button clicked event not triggering after lost focus event

I have a Winforms c# form with some comboBoxes , cancel and save buttons that work fine.
I now need to capture when the user has finished entering text into a comboBox.
I add an empty ( for now) lostFocus (or Leave) event to the combbox , which triggers fine. However if the cause of that event was a cancel or save button press , the corresponding event is no longer triggered. These buttons still work fine if pressed at other times.
Should these two event be firing in sequence or is there some better way to capture completed text entry?
The Leave and/or LoseFocus events do not get triggered because you do not leave the combobox and because it doesn't lose focus when you press Enter or Escape.
Therefore the best way is to add the function you are triggering in the LoseFocus event, also to the Button click events of the Cancel- and the Accept-Buttons.
Adding a call to the leave event itself: comboBox1.Leave(null, null); would be the simplest way.
To make sure that the function is called only once, I check who has focus in the ButtonClick events:
private void acceptButton_Click(object sender, EventArgs e)
{
if (comboBox1.ContainsFocus) comboBox1_Leave(acceptButton, null);
// do accept stuff here..
}
private void cancelButton_Click(object sender, EventArgs e)
{
if (comboBox1.ContainsFocus) comboBox1_Leave(cancelButton, null);
// do cancel stuff here..
}
private void comboBox1_Leave(object sender, EventArgs e)
{
// do leave stuff here..
Console.WriteLine(sender);
}
I also pass in the Button so you could check the sender to see how the Leave was triggered..
I'm answering my own question here as I feel it might be useful to other newbies.
The breakpoint I had set in my empty lostFocus event was stopping button click event from occurring. When I removed the breakpoint the problem went away.
However when I added code to my lostFocus event, a form redraw was sometimes moving the buttons and preventing their events from firing. To solve this problem I adapted TaWs very useful answer and fired the button event from within the lostFocus event.
private void comboBox1_LostFocus(object sender, EventArgs e)
{
bool saving = btnSave.ContainsFocus;
// form redraw stuff here..
if (saving)
btnSave_Click(btnSave, null);
}

Onclick event for textbox in csharp form application

I'm creating form application on c# . I have dragged a textbox with some text in it.
private void textBox1_Click(object sender, EventArgs e)
{
}
Now what is the event for the onlick on textBox1 ?
I need to add this on that function textBox1.Clear();
P.S I searched everywhere. But all i can find is jquery and javascripts... No c#.
EDIT
I tried onfocus like below..but its not working
private void textBox1_OnFocus(object sender, EventArgs e)
{
MessageBox.Show("dsd");
}
If you want to do something when the control is clicked the handle the Click event, not the TextChanged event. Presumably you just double-clicked the control in the designer. That will only handle the default event. To handle other events, open the Properties window, click the Events button at the top and then double-click the appropriate event.
That said, is Click really appropriate? What if the user enters the TextBox using the Tab key? If what you actually want to do is act when the control gets focus then you should handle the Enter event.
You can handle OnFocus/GotGocus event in the TextBox, and clear the text in the textbox.
Hope this helps.

How to generate events automatically for buttons without creating manually from properties if there are 'n' number of buttons?

IDE: Visual Studio 2010
Language: c# .net
I am generating events for buttons manually from properties. But, its becoming very lengthy process if there are suppose 20 buttons doing the same task like 'Mouse Hover' and 'Mouse Leave' . So, is there a way to copy events for all the other buttons ?
You can subscribe all your buttons to same event handler:
foreach(var button in Controls.OfType<Button>())
{
button.MouseHover += Button_MouseHover; // add handler
button.MouseLeave += Button_MouseLeave;
}
In that handler you can determine which exact button raised even by casting event source to button type:
private void Button_MouseHover(object sender, EventArgs e)
{
var button = (Button)sender; // sender is one of buttons
// use button.Name
}
Code above subscribes to events of all buttons. But if you want to filter them (e.g. by name) you can add filtering:
Controls.OfType<Button>().Where(b => b.Name.StartsWith("foo"))
Buttons can all share the same event, there's no need to have a seperate event for each button if they're doing similar tasks. (The object sender parameter will give you the Control which was clicked.
IF you select all the buttons (by keeping the ctrl key pressed) in the designer, you can then easily assign 1 event to all 20 buttons
In life you will not find shortcuts for everything,
In short there is no shortcut, but yes as mentioned in other post if you have same event handler and same action to be taken then this will help you reduce your work.
You don't have to do this manually, you can add event handlers from code as well. Also, if the logic is quite similar for all the buttons then you can use single event handler for all of them. Every event handler has sender property what will be set to the button that caused event.
Simple example would be something like this:
//at first assign event handlers
button1.Click += new EventHandler(Button_Click);
button2.Click += new EventHandler(Button_Click);
//single event handler
private void Button_Click(object sender, System.EventArgs e)
{
// Add event handler code here.
Debug.WriteLine("You clicked: {0}", sender);
}

Check for Button Click Event on Form - C#

I currently have a form with about 13 buttons on it.
I want to be able to perform a function when one of those buttons are clicked. But I am trying to keep from having 13 different button click events.
Is there some way for me to be able to determine when any button click event is fired, and be able to tell which button fired it?
Thanks!
Have one function that handles all of the click events and use the properties of the 'sender' object to identify the specific button.
You can have different button click handlers, and name them according to button actions, also you can have single event handler for all of them, in this case parameter sender can be cast to button and for example by it's name, finding related button.
But I offer if you have similar behavior on group of buttons map them to a single function, but if actions are different using different method is better, but in all one form with 13 button is not good, you can change them to menu, Tab, ...
foreach (Control ctl in this.Controls)
{
if (ctl is Button)
(ctl as Button).Click += MyButtonHandler;
}
protected void MyButtonHandler(object sender, EventArgs e)
{
Button clickedButton = sender as Button;
//...
}
The first parameter to the callback function is the button that was pressed.
private void OnButtonClicked(object sender, EventArgs e){
Button oButton = sender as Button;
if (oButton != null){
// your logic goes here !
}
}
oButton variables is your current button. (important to check if oButton != null when using as operator)
on the click event you get a reference to the Sender - this is the clicked button so inside that you could test for the Content or Tag and act based on the value:
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show((sender as Button).Tag.ToString());
}
I think that in this situation using delgates would be proper. Check these links out for further information on implementation.
The C# Station Tutorial: Introduction to Delegates and Events
Delegates and Events in C# / .NET
Every proper eventhandler has an Object sender parameter. Give all 13 buttons the same handler by typing the same name in the Properties window OnClick event, for instance: OnAnyButtonClicked. The created function will be:
private void OnAnyButtonClicked(object sender, ...)
{
// sender is the button that was clicked,
// find out which button is clicked
// call the corresponding function
}
Tip:
To find out which button is pressed you could use Object.ReferenceEquals
A faster way to avoid if ... then ... else if ... then ... else if...
is using the Tag property of each Button.
Give eacht Button.Tag an enum value corresponding to the action that has to be performed and use a switch statement to find out what has to be done.
You could also assing a delegate to the button.Tag, but that is almost the same as making a different onClick event handler for every button.

Equivalent of WinForms TextBox.Validating event in WPF

In WinForms I could handle the Validated event to do something after the user changed text in a TextBox. Unlike TextChanged, Validated didn't fire for every character change; it only fired when the user was done.
Is there anything in WPF I can use to get the same result, an event raised only after the user is done changing the text?
LostFocus will fire when the user moves from your textbox onto any other control.
It seems that there is no native solution.
The LostFocus event is a good idea. But when the user click on Enter, he wants the TextBox to validate the change.
So here is my suggestion : use the LostFocus event and the KeyDown event when the key is Enter.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
// code to lauch after validation
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// call the LostFocus event to validate the TextBox
((TextBox)sender).RaiseEvent(new RoutedEventArgs(TextBox.LostFocusEvent));
}
}
LostFocus is not equivalent to Validate. It creates lots of problem when you have multiple text boxes on one screen and every text box has some logic written in Validate. In validate event you can control focus easily but not in LostFocus so easily.
You can also try Binding.ValidationRules
Documented at : http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules.aspx
Here is the article to get started:
How to implement binding validations :
http://msdn.microsoft.com/en-us/library/ms753962.aspx

Categories

Resources